From 017dc7e322a530032a2dfefe2aebd8aa81be8104 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 21 Feb 2023 20:12:22 +0000 Subject: [PATCH 1/2] feat: Added Training and Evaluation functions, request, responses and metadata to document_processor_service.proto feat: Added evaluation.proto feat: Added latest_evaluation to processor.proto chore: removed deprecated flag from REPLACE in OperationType in document.proto PiperOrigin-RevId: 511230520 Source-Link: https://github.com/googleapis/googleapis/commit/c53bf8d535e342737aa479cbe2cdead26507cdf4 Source-Link: https://github.com/googleapis/googleapis-gen/commit/5693cbc98b6412085ff6d3aba719b68e307c5357 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTY5M2NiYzk4YjY0MTIwODVmZjZkM2FiYTcxOWI2OGUzMDdjNTM1NyJ9 --- owl-bot-staging/v1/.coveragerc | 13 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 + .../document_processor_service.rst | 10 + .../v1/docs/documentai_v1/services.rst | 6 + .../v1/docs/documentai_v1/types.rst | 6 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/documentai/__init__.py | 161 + .../google/cloud/documentai/gapic_version.py | 16 + .../v1/google/cloud/documentai/py.typed | 2 + .../v1/google/cloud/documentai_v1/__init__.py | 162 + .../cloud/documentai_v1/gapic_metadata.json | 358 + .../cloud/documentai_v1/gapic_version.py | 16 + .../v1/google/cloud/documentai_v1/py.typed | 2 + .../cloud/documentai_v1/services/__init__.py | 15 + .../document_processor_service/__init__.py | 22 + .../async_client.py | 2979 ++++ .../document_processor_service/client.py | 3196 ++++ .../document_processor_service/pagers.py | 505 + .../transports/__init__.py | 38 + .../transports/base.py | 519 + .../transports/grpc.py | 945 ++ .../transports/grpc_asyncio.py | 944 ++ .../transports/rest.py | 3288 ++++ .../cloud/documentai_v1/types/__init__.py | 172 + .../cloud/documentai_v1/types/barcode.py | 85 + .../cloud/documentai_v1/types/document.py | 1708 ++ .../cloud/documentai_v1/types/document_io.py | 221 + .../types/document_processor_service.py | 1361 ++ .../documentai_v1/types/document_schema.py | 250 + .../cloud/documentai_v1/types/evaluation.py | 342 + .../cloud/documentai_v1/types/geometry.py | 99 + .../documentai_v1/types/operation_metadata.py | 96 + .../cloud/documentai_v1/types/processor.py | 285 + .../documentai_v1/types/processor_type.py | 106 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 184 + ...r_service_batch_process_documents_async.py | 56 + ...or_service_batch_process_documents_sync.py | 56 + ...rocessor_service_create_processor_async.py | 52 + ...processor_service_create_processor_sync.py | 52 + ...rocessor_service_delete_processor_async.py | 56 + ...processor_service_delete_processor_sync.py | 56 + ..._service_delete_processor_version_async.py | 56 + ...r_service_delete_processor_version_sync.py | 56 + ..._service_deploy_processor_version_async.py | 56 + ...r_service_deploy_processor_version_sync.py | 56 + ...ocessor_service_disable_processor_async.py | 56 + ...rocessor_service_disable_processor_sync.py | 56 + ...rocessor_service_enable_processor_async.py | 56 + ...processor_service_enable_processor_sync.py | 56 + ...ervice_evaluate_processor_version_async.py | 56 + ...service_evaluate_processor_version_sync.py | 56 + ...sor_service_fetch_processor_types_async.py | 52 + ...ssor_service_fetch_processor_types_sync.py | 52 + ..._processor_service_get_evaluation_async.py | 52 + ...t_processor_service_get_evaluation_sync.py | 52 + ...t_processor_service_get_processor_async.py | 52 + ...nt_processor_service_get_processor_sync.py | 52 + ...cessor_service_get_processor_type_async.py | 52 + ...ocessor_service_get_processor_type_sync.py | 52 + ...sor_service_get_processor_version_async.py | 52 + ...ssor_service_get_processor_version_sync.py | 52 + ...rocessor_service_list_evaluations_async.py | 53 + ...processor_service_list_evaluations_sync.py | 53 + ...ssor_service_list_processor_types_async.py | 53 + ...essor_service_list_processor_types_sync.py | 53 + ...r_service_list_processor_versions_async.py | 53 + ...or_service_list_processor_versions_sync.py | 53 + ...processor_service_list_processors_async.py | 53 + ..._processor_service_list_processors_sync.py | 53 + ...rocessor_service_process_document_async.py | 56 + ...processor_service_process_document_sync.py | 56 + ...processor_service_review_document_async.py | 60 + ..._processor_service_review_document_sync.py | 60 + ...ice_set_default_processor_version_async.py | 57 + ...vice_set_default_processor_version_sync.py | 57 + ...r_service_train_processor_version_async.py | 56 + ...or_service_train_processor_version_sync.py | 56 + ...ervice_undeploy_processor_version_async.py | 56 + ...service_undeploy_processor_version_sync.py | 56 + ...t_metadata_google.cloud.documentai.v1.json | 3549 +++++ .../scripts/fixup_documentai_v1_keywords.py | 197 + owl-bot-staging/v1/setup.py | 91 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/documentai_v1/__init__.py | 16 + .../test_document_processor_service.py | 13252 +++++++++++++++ owl-bot-staging/v1beta2/.coveragerc | 13 + owl-bot-staging/v1beta2/.flake8 | 33 + owl-bot-staging/v1beta2/MANIFEST.in | 2 + owl-bot-staging/v1beta2/README.rst | 49 + owl-bot-staging/v1beta2/docs/conf.py | 376 + .../document_understanding_service.rst | 6 + .../docs/documentai_v1beta2/services.rst | 6 + .../v1beta2/docs/documentai_v1beta2/types.rst | 6 + owl-bot-staging/v1beta2/docs/index.rst | 7 + .../google/cloud/documentai/__init__.py | 67 + .../google/cloud/documentai/gapic_version.py | 16 + .../v1beta2/google/cloud/documentai/py.typed | 2 + .../cloud/documentai_v1beta2/__init__.py | 68 + .../documentai_v1beta2/gapic_metadata.json | 43 + .../cloud/documentai_v1beta2/gapic_version.py | 16 + .../google/cloud/documentai_v1beta2/py.typed | 2 + .../documentai_v1beta2/services/__init__.py | 15 + .../__init__.py | 22 + .../async_client.py | 426 + .../document_understanding_service/client.py | 606 + .../transports/__init__.py | 33 + .../transports/base.py | 184 + .../transports/grpc.py | 313 + .../transports/grpc_asyncio.py | 312 + .../documentai_v1beta2/types/__init__.py | 64 + .../documentai_v1beta2/types/document.py | 1080 ++ .../types/document_understanding.py | 591 + .../documentai_v1beta2/types/geometry.py | 97 + owl-bot-staging/v1beta2/mypy.ini | 3 + owl-bot-staging/v1beta2/noxfile.py | 184 + ...g_service_batch_process_documents_async.py | 60 + ...ng_service_batch_process_documents_sync.py | 60 + ...standing_service_process_document_async.py | 56 + ...rstanding_service_process_document_sync.py | 56 + ...adata_google.cloud.documentai.v1beta2.json | 329 + .../fixup_documentai_v1beta2_keywords.py | 177 + owl-bot-staging/v1beta2/setup.py | 90 + .../v1beta2/testing/constraints-3.10.txt | 6 + .../v1beta2/testing/constraints-3.11.txt | 6 + .../v1beta2/testing/constraints-3.12.txt | 6 + .../v1beta2/testing/constraints-3.7.txt | 9 + .../v1beta2/testing/constraints-3.8.txt | 6 + .../v1beta2/testing/constraints-3.9.txt | 6 + owl-bot-staging/v1beta2/tests/__init__.py | 16 + .../v1beta2/tests/unit/__init__.py | 16 + .../v1beta2/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/documentai_v1beta2/__init__.py | 16 + .../test_document_understanding_service.py | 1570 ++ owl-bot-staging/v1beta3/.coveragerc | 13 + owl-bot-staging/v1beta3/.flake8 | 33 + owl-bot-staging/v1beta3/MANIFEST.in | 2 + owl-bot-staging/v1beta3/README.rst | 49 + owl-bot-staging/v1beta3/docs/conf.py | 376 + .../document_processor_service.rst | 10 + .../docs/documentai_v1beta3/services.rst | 6 + .../v1beta3/docs/documentai_v1beta3/types.rst | 6 + owl-bot-staging/v1beta3/docs/index.rst | 7 + .../google/cloud/documentai/__init__.py | 165 + .../google/cloud/documentai/gapic_version.py | 16 + .../v1beta3/google/cloud/documentai/py.typed | 2 + .../cloud/documentai_v1beta3/__init__.py | 166 + .../documentai_v1beta3/gapic_metadata.json | 358 + .../cloud/documentai_v1beta3/gapic_version.py | 16 + .../google/cloud/documentai_v1beta3/py.typed | 2 + .../documentai_v1beta3/services/__init__.py | 15 + .../document_processor_service/__init__.py | 22 + .../async_client.py | 2981 ++++ .../document_processor_service/client.py | 3198 ++++ .../document_processor_service/pagers.py | 505 + .../transports/__init__.py | 38 + .../transports/base.py | 519 + .../transports/grpc.py | 945 ++ .../transports/grpc_asyncio.py | 944 ++ .../transports/rest.py | 3280 ++++ .../documentai_v1beta3/types/__init__.py | 176 + .../cloud/documentai_v1beta3/types/barcode.py | 85 + .../documentai_v1beta3/types/document.py | 1712 ++ .../documentai_v1beta3/types/document_io.py | 245 + .../types/document_processor_service.py | 1534 ++ .../types/document_schema.py | 242 + .../documentai_v1beta3/types/evaluation.py | 342 + .../documentai_v1beta3/types/geometry.py | 99 + .../types/operation_metadata.py | 96 + .../documentai_v1beta3/types/processor.py | 285 + .../types/processor_type.py | 106 + owl-bot-staging/v1beta3/mypy.ini | 3 + owl-bot-staging/v1beta3/noxfile.py | 184 + ...r_service_batch_process_documents_async.py | 56 + ...or_service_batch_process_documents_sync.py | 56 + ...rocessor_service_create_processor_async.py | 52 + ...processor_service_create_processor_sync.py | 52 + ...rocessor_service_delete_processor_async.py | 56 + ...processor_service_delete_processor_sync.py | 56 + ..._service_delete_processor_version_async.py | 56 + ...r_service_delete_processor_version_sync.py | 56 + ..._service_deploy_processor_version_async.py | 56 + ...r_service_deploy_processor_version_sync.py | 56 + ...ocessor_service_disable_processor_async.py | 56 + ...rocessor_service_disable_processor_sync.py | 56 + ...rocessor_service_enable_processor_async.py | 56 + ...processor_service_enable_processor_sync.py | 56 + ...ervice_evaluate_processor_version_async.py | 56 + ...service_evaluate_processor_version_sync.py | 56 + ...sor_service_fetch_processor_types_async.py | 52 + ...ssor_service_fetch_processor_types_sync.py | 52 + ..._processor_service_get_evaluation_async.py | 52 + ...t_processor_service_get_evaluation_sync.py | 52 + ...t_processor_service_get_processor_async.py | 52 + ...nt_processor_service_get_processor_sync.py | 52 + ...cessor_service_get_processor_type_async.py | 52 + ...ocessor_service_get_processor_type_sync.py | 52 + ...sor_service_get_processor_version_async.py | 52 + ...ssor_service_get_processor_version_sync.py | 52 + ...rocessor_service_list_evaluations_async.py | 53 + ...processor_service_list_evaluations_sync.py | 53 + ...ssor_service_list_processor_types_async.py | 53 + ...essor_service_list_processor_types_sync.py | 53 + ...r_service_list_processor_versions_async.py | 53 + ...or_service_list_processor_versions_sync.py | 53 + ...processor_service_list_processors_async.py | 53 + ..._processor_service_list_processors_sync.py | 53 + ...rocessor_service_process_document_async.py | 56 + ...processor_service_process_document_sync.py | 56 + ...processor_service_review_document_async.py | 60 + ..._processor_service_review_document_sync.py | 60 + ...ice_set_default_processor_version_async.py | 57 + ...vice_set_default_processor_version_sync.py | 57 + ...r_service_train_processor_version_async.py | 56 + ...or_service_train_processor_version_sync.py | 56 + ...ervice_undeploy_processor_version_async.py | 56 + ...service_undeploy_processor_version_sync.py | 56 + ...adata_google.cloud.documentai.v1beta3.json | 3549 +++++ .../fixup_documentai_v1beta3_keywords.py | 197 + owl-bot-staging/v1beta3/setup.py | 90 + .../v1beta3/testing/constraints-3.10.txt | 6 + .../v1beta3/testing/constraints-3.11.txt | 6 + .../v1beta3/testing/constraints-3.12.txt | 6 + .../v1beta3/testing/constraints-3.7.txt | 9 + .../v1beta3/testing/constraints-3.8.txt | 6 + .../v1beta3/testing/constraints-3.9.txt | 6 + owl-bot-staging/v1beta3/tests/__init__.py | 16 + .../v1beta3/tests/unit/__init__.py | 16 + .../v1beta3/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/documentai_v1beta3/__init__.py | 16 + .../test_document_processor_service.py | 13258 ++++++++++++++++ 242 files changed, 83707 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst create mode 100644 owl-bot-staging/v1/docs/documentai_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/documentai_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/documentai/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/evaluation.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py create mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py create mode 100644 owl-bot-staging/v1beta2/.coveragerc create mode 100644 owl-bot-staging/v1beta2/.flake8 create mode 100644 owl-bot-staging/v1beta2/MANIFEST.in create mode 100644 owl-bot-staging/v1beta2/README.rst create mode 100644 owl-bot-staging/v1beta2/docs/conf.py create mode 100644 owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst create mode 100644 owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst create mode 100644 owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst create mode 100644 owl-bot-staging/v1beta2/docs/index.rst create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai/py.typed create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py create mode 100644 owl-bot-staging/v1beta2/mypy.ini create mode 100644 owl-bot-staging/v1beta2/noxfile.py create mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py create mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py create mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py create mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py create mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json create mode 100644 owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py create mode 100644 owl-bot-staging/v1beta2/setup.py create mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1beta2/tests/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py create mode 100644 owl-bot-staging/v1beta3/.coveragerc create mode 100644 owl-bot-staging/v1beta3/.flake8 create mode 100644 owl-bot-staging/v1beta3/MANIFEST.in create mode 100644 owl-bot-staging/v1beta3/README.rst create mode 100644 owl-bot-staging/v1beta3/docs/conf.py create mode 100644 owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst create mode 100644 owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst create mode 100644 owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst create mode 100644 owl-bot-staging/v1beta3/docs/index.rst create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai/py.typed create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py create mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py create mode 100644 owl-bot-staging/v1beta3/mypy.ini create mode 100644 owl-bot-staging/v1beta3/noxfile.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py create mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json create mode 100644 owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py create mode 100644 owl-bot-staging/v1beta3/setup.py create mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1beta3/tests/__init__.py create mode 100644 owl-bot-staging/v1beta3/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py create mode 100644 owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..46ab6093 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/documentai/__init__.py + google/cloud/documentai/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 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 +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 00000000..b804f157 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/documentai *.py +recursive-include google/cloud/documentai_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..484a3c1c --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Documentai API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Documentai API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..960a15f0 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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. +# +# +# google-cloud-documentai documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-documentai" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-documentai-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-documentai.tex", + u"google-cloud-documentai Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-documentai", + u"Google Cloud Documentai Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-documentai", + u"google-cloud-documentai Documentation", + author, + "google-cloud-documentai", + "GAPIC library for Google Cloud Documentai API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst b/owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst new file mode 100644 index 00000000..5288f946 --- /dev/null +++ b/owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst @@ -0,0 +1,10 @@ +DocumentProcessorService +------------------------------------------ + +.. automodule:: google.cloud.documentai_v1.services.document_processor_service + :members: + :inherited-members: + +.. automodule:: google.cloud.documentai_v1.services.document_processor_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/documentai_v1/services.rst b/owl-bot-staging/v1/docs/documentai_v1/services.rst new file mode 100644 index 00000000..551bb666 --- /dev/null +++ b/owl-bot-staging/v1/docs/documentai_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Documentai v1 API +=========================================== +.. toctree:: + :maxdepth: 2 + + document_processor_service diff --git a/owl-bot-staging/v1/docs/documentai_v1/types.rst b/owl-bot-staging/v1/docs/documentai_v1/types.rst new file mode 100644 index 00000000..ddfb0aac --- /dev/null +++ b/owl-bot-staging/v1/docs/documentai_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Documentai v1 API +======================================== + +.. automodule:: google.cloud.documentai_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..c907db5b --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + documentai_v1/services + documentai_v1/types diff --git a/owl-bot-staging/v1/google/cloud/documentai/__init__.py b/owl-bot-staging/v1/google/cloud/documentai/__init__.py new file mode 100644 index 00000000..cc8377eb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai/__init__.py @@ -0,0 +1,161 @@ +# -*- 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 google.cloud.documentai import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.documentai_v1.services.document_processor_service.client import DocumentProcessorServiceClient +from google.cloud.documentai_v1.services.document_processor_service.async_client import DocumentProcessorServiceAsyncClient + +from google.cloud.documentai_v1.types.barcode import Barcode +from google.cloud.documentai_v1.types.document import Document +from google.cloud.documentai_v1.types.document_io import BatchDocumentsInputConfig +from google.cloud.documentai_v1.types.document_io import DocumentOutputConfig +from google.cloud.documentai_v1.types.document_io import GcsDocument +from google.cloud.documentai_v1.types.document_io import GcsDocuments +from google.cloud.documentai_v1.types.document_io import GcsPrefix +from google.cloud.documentai_v1.types.document_io import RawDocument +from google.cloud.documentai_v1.types.document_processor_service import BatchProcessMetadata +from google.cloud.documentai_v1.types.document_processor_service import BatchProcessRequest +from google.cloud.documentai_v1.types.document_processor_service import BatchProcessResponse +from google.cloud.documentai_v1.types.document_processor_service import CreateProcessorRequest +from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorMetadata +from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorRequest +from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorVersionMetadata +from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorVersionRequest +from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionMetadata +from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionRequest +from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionResponse +from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorMetadata +from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorRequest +from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorResponse +from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorMetadata +from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorRequest +from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorResponse +from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionMetadata +from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionRequest +from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionResponse +from google.cloud.documentai_v1.types.document_processor_service import FetchProcessorTypesRequest +from google.cloud.documentai_v1.types.document_processor_service import FetchProcessorTypesResponse +from google.cloud.documentai_v1.types.document_processor_service import GetEvaluationRequest +from google.cloud.documentai_v1.types.document_processor_service import GetProcessorRequest +from google.cloud.documentai_v1.types.document_processor_service import GetProcessorTypeRequest +from google.cloud.documentai_v1.types.document_processor_service import GetProcessorVersionRequest +from google.cloud.documentai_v1.types.document_processor_service import HumanReviewStatus +from google.cloud.documentai_v1.types.document_processor_service import ListEvaluationsRequest +from google.cloud.documentai_v1.types.document_processor_service import ListEvaluationsResponse +from google.cloud.documentai_v1.types.document_processor_service import ListProcessorsRequest +from google.cloud.documentai_v1.types.document_processor_service import ListProcessorsResponse +from google.cloud.documentai_v1.types.document_processor_service import ListProcessorTypesRequest +from google.cloud.documentai_v1.types.document_processor_service import ListProcessorTypesResponse +from google.cloud.documentai_v1.types.document_processor_service import ListProcessorVersionsRequest +from google.cloud.documentai_v1.types.document_processor_service import ListProcessorVersionsResponse +from google.cloud.documentai_v1.types.document_processor_service import ProcessRequest +from google.cloud.documentai_v1.types.document_processor_service import ProcessResponse +from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentOperationMetadata +from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentRequest +from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentResponse +from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionMetadata +from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionRequest +from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionResponse +from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionMetadata +from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionRequest +from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionResponse +from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionMetadata +from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionRequest +from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionResponse +from google.cloud.documentai_v1.types.document_schema import DocumentSchema +from google.cloud.documentai_v1.types.evaluation import Evaluation +from google.cloud.documentai_v1.types.evaluation import EvaluationReference +from google.cloud.documentai_v1.types.geometry import BoundingPoly +from google.cloud.documentai_v1.types.geometry import NormalizedVertex +from google.cloud.documentai_v1.types.geometry import Vertex +from google.cloud.documentai_v1.types.operation_metadata import CommonOperationMetadata +from google.cloud.documentai_v1.types.processor import Processor +from google.cloud.documentai_v1.types.processor import ProcessorVersion +from google.cloud.documentai_v1.types.processor_type import ProcessorType + +__all__ = ('DocumentProcessorServiceClient', + 'DocumentProcessorServiceAsyncClient', + 'Barcode', + 'Document', + 'BatchDocumentsInputConfig', + 'DocumentOutputConfig', + 'GcsDocument', + 'GcsDocuments', + 'GcsPrefix', + 'RawDocument', + 'BatchProcessMetadata', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'CreateProcessorRequest', + 'DeleteProcessorMetadata', + 'DeleteProcessorRequest', + 'DeleteProcessorVersionMetadata', + 'DeleteProcessorVersionRequest', + 'DeployProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DisableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'EnableProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EvaluateProcessorVersionMetadata', + 'EvaluateProcessorVersionRequest', + 'EvaluateProcessorVersionResponse', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetEvaluationRequest', + 'GetProcessorRequest', + 'GetProcessorTypeRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListEvaluationsRequest', + 'ListEvaluationsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'TrainProcessorVersionMetadata', + 'TrainProcessorVersionRequest', + 'TrainProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + 'Evaluation', + 'EvaluationReference', + 'BoundingPoly', + 'NormalizedVertex', + 'Vertex', + 'CommonOperationMetadata', + 'Processor', + 'ProcessorVersion', + 'ProcessorType', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai/gapic_version.py b/owl-bot-staging/v1/google/cloud/documentai/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/documentai/py.typed b/owl-bot-staging/v1/google/cloud/documentai/py.typed new file mode 100644 index 00000000..81b45001 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py new file mode 100644 index 00000000..35549fa5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py @@ -0,0 +1,162 @@ +# -*- 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 google.cloud.documentai_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.document_processor_service import DocumentProcessorServiceClient +from .services.document_processor_service import DocumentProcessorServiceAsyncClient + +from .types.barcode import Barcode +from .types.document import Document +from .types.document_io import BatchDocumentsInputConfig +from .types.document_io import DocumentOutputConfig +from .types.document_io import GcsDocument +from .types.document_io import GcsDocuments +from .types.document_io import GcsPrefix +from .types.document_io import RawDocument +from .types.document_processor_service import BatchProcessMetadata +from .types.document_processor_service import BatchProcessRequest +from .types.document_processor_service import BatchProcessResponse +from .types.document_processor_service import CreateProcessorRequest +from .types.document_processor_service import DeleteProcessorMetadata +from .types.document_processor_service import DeleteProcessorRequest +from .types.document_processor_service import DeleteProcessorVersionMetadata +from .types.document_processor_service import DeleteProcessorVersionRequest +from .types.document_processor_service import DeployProcessorVersionMetadata +from .types.document_processor_service import DeployProcessorVersionRequest +from .types.document_processor_service import DeployProcessorVersionResponse +from .types.document_processor_service import DisableProcessorMetadata +from .types.document_processor_service import DisableProcessorRequest +from .types.document_processor_service import DisableProcessorResponse +from .types.document_processor_service import EnableProcessorMetadata +from .types.document_processor_service import EnableProcessorRequest +from .types.document_processor_service import EnableProcessorResponse +from .types.document_processor_service import EvaluateProcessorVersionMetadata +from .types.document_processor_service import EvaluateProcessorVersionRequest +from .types.document_processor_service import EvaluateProcessorVersionResponse +from .types.document_processor_service import FetchProcessorTypesRequest +from .types.document_processor_service import FetchProcessorTypesResponse +from .types.document_processor_service import GetEvaluationRequest +from .types.document_processor_service import GetProcessorRequest +from .types.document_processor_service import GetProcessorTypeRequest +from .types.document_processor_service import GetProcessorVersionRequest +from .types.document_processor_service import HumanReviewStatus +from .types.document_processor_service import ListEvaluationsRequest +from .types.document_processor_service import ListEvaluationsResponse +from .types.document_processor_service import ListProcessorsRequest +from .types.document_processor_service import ListProcessorsResponse +from .types.document_processor_service import ListProcessorTypesRequest +from .types.document_processor_service import ListProcessorTypesResponse +from .types.document_processor_service import ListProcessorVersionsRequest +from .types.document_processor_service import ListProcessorVersionsResponse +from .types.document_processor_service import ProcessRequest +from .types.document_processor_service import ProcessResponse +from .types.document_processor_service import ReviewDocumentOperationMetadata +from .types.document_processor_service import ReviewDocumentRequest +from .types.document_processor_service import ReviewDocumentResponse +from .types.document_processor_service import SetDefaultProcessorVersionMetadata +from .types.document_processor_service import SetDefaultProcessorVersionRequest +from .types.document_processor_service import SetDefaultProcessorVersionResponse +from .types.document_processor_service import TrainProcessorVersionMetadata +from .types.document_processor_service import TrainProcessorVersionRequest +from .types.document_processor_service import TrainProcessorVersionResponse +from .types.document_processor_service import UndeployProcessorVersionMetadata +from .types.document_processor_service import UndeployProcessorVersionRequest +from .types.document_processor_service import UndeployProcessorVersionResponse +from .types.document_schema import DocumentSchema +from .types.evaluation import Evaluation +from .types.evaluation import EvaluationReference +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Vertex +from .types.operation_metadata import CommonOperationMetadata +from .types.processor import Processor +from .types.processor import ProcessorVersion +from .types.processor_type import ProcessorType + +__all__ = ( + 'DocumentProcessorServiceAsyncClient', +'Barcode', +'BatchDocumentsInputConfig', +'BatchProcessMetadata', +'BatchProcessRequest', +'BatchProcessResponse', +'BoundingPoly', +'CommonOperationMetadata', +'CreateProcessorRequest', +'DeleteProcessorMetadata', +'DeleteProcessorRequest', +'DeleteProcessorVersionMetadata', +'DeleteProcessorVersionRequest', +'DeployProcessorVersionMetadata', +'DeployProcessorVersionRequest', +'DeployProcessorVersionResponse', +'DisableProcessorMetadata', +'DisableProcessorRequest', +'DisableProcessorResponse', +'Document', +'DocumentOutputConfig', +'DocumentProcessorServiceClient', +'DocumentSchema', +'EnableProcessorMetadata', +'EnableProcessorRequest', +'EnableProcessorResponse', +'EvaluateProcessorVersionMetadata', +'EvaluateProcessorVersionRequest', +'EvaluateProcessorVersionResponse', +'Evaluation', +'EvaluationReference', +'FetchProcessorTypesRequest', +'FetchProcessorTypesResponse', +'GcsDocument', +'GcsDocuments', +'GcsPrefix', +'GetEvaluationRequest', +'GetProcessorRequest', +'GetProcessorTypeRequest', +'GetProcessorVersionRequest', +'HumanReviewStatus', +'ListEvaluationsRequest', +'ListEvaluationsResponse', +'ListProcessorTypesRequest', +'ListProcessorTypesResponse', +'ListProcessorVersionsRequest', +'ListProcessorVersionsResponse', +'ListProcessorsRequest', +'ListProcessorsResponse', +'NormalizedVertex', +'ProcessRequest', +'ProcessResponse', +'Processor', +'ProcessorType', +'ProcessorVersion', +'RawDocument', +'ReviewDocumentOperationMetadata', +'ReviewDocumentRequest', +'ReviewDocumentResponse', +'SetDefaultProcessorVersionMetadata', +'SetDefaultProcessorVersionRequest', +'SetDefaultProcessorVersionResponse', +'TrainProcessorVersionMetadata', +'TrainProcessorVersionRequest', +'TrainProcessorVersionResponse', +'UndeployProcessorVersionMetadata', +'UndeployProcessorVersionRequest', +'UndeployProcessorVersionResponse', +'Vertex', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json new file mode 100644 index 00000000..863c39a3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json @@ -0,0 +1,358 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.documentai_v1", + "protoPackage": "google.cloud.documentai.v1", + "schema": "1.0", + "services": { + "DocumentProcessorService": { + "clients": { + "grpc": { + "libraryClient": "DocumentProcessorServiceClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeleteProcessorVersion": { + "methods": [ + "delete_processor_version" + ] + }, + "DeployProcessorVersion": { + "methods": [ + "deploy_processor_version" + ] + }, + "DisableProcessor": { + "methods": [ + "disable_processor" + ] + }, + "EnableProcessor": { + "methods": [ + "enable_processor" + ] + }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorType": { + "methods": [ + "get_processor_type" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListProcessorTypes": { + "methods": [ + "list_processor_types" + ] + }, + "ListProcessorVersions": { + "methods": [ + "list_processor_versions" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + }, + "ReviewDocument": { + "methods": [ + "review_document" + ] + }, + "SetDefaultProcessorVersion": { + "methods": [ + "set_default_processor_version" + ] + }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentProcessorServiceAsyncClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeleteProcessorVersion": { + "methods": [ + "delete_processor_version" + ] + }, + "DeployProcessorVersion": { + "methods": [ + "deploy_processor_version" + ] + }, + "DisableProcessor": { + "methods": [ + "disable_processor" + ] + }, + "EnableProcessor": { + "methods": [ + "enable_processor" + ] + }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorType": { + "methods": [ + "get_processor_type" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListProcessorTypes": { + "methods": [ + "list_processor_types" + ] + }, + "ListProcessorVersions": { + "methods": [ + "list_processor_versions" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + }, + "ReviewDocument": { + "methods": [ + "review_document" + ] + }, + "SetDefaultProcessorVersion": { + "methods": [ + "set_default_processor_version" + ] + }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_version" + ] + } + } + }, + "rest": { + "libraryClient": "DocumentProcessorServiceClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeleteProcessorVersion": { + "methods": [ + "delete_processor_version" + ] + }, + "DeployProcessorVersion": { + "methods": [ + "deploy_processor_version" + ] + }, + "DisableProcessor": { + "methods": [ + "disable_processor" + ] + }, + "EnableProcessor": { + "methods": [ + "enable_processor" + ] + }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorType": { + "methods": [ + "get_processor_type" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListProcessorTypes": { + "methods": [ + "list_processor_types" + ] + }, + "ListProcessorVersions": { + "methods": [ + "list_processor_versions" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + }, + "ReviewDocument": { + "methods": [ + "review_document" + ] + }, + "SetDefaultProcessorVersion": { + "methods": [ + "set_default_processor_version" + ] + }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/py.typed b/owl-bot-staging/v1/google/cloud/documentai_v1/py.typed new file mode 100644 index 00000000..81b45001 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py new file mode 100644 index 00000000..0e16e431 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 .client import DocumentProcessorServiceClient +from .async_client import DocumentProcessorServiceAsyncClient + +__all__ = ( + 'DocumentProcessorServiceClient', + 'DocumentProcessorServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py new file mode 100644 index 00000000..c3f43e68 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py @@ -0,0 +1,2979 @@ +# -*- 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 collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.documentai_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.documentai_v1.services.document_processor_service import pagers +from google.cloud.documentai_v1.types import document +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import document_schema +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport +from .client import DocumentProcessorServiceClient + + +class DocumentProcessorServiceAsyncClient: + """Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + """ + + _client: DocumentProcessorServiceClient + + 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) + parse_human_review_config_path = staticmethod(DocumentProcessorServiceClient.parse_human_review_config_path) + processor_path = staticmethod(DocumentProcessorServiceClient.processor_path) + parse_processor_path = staticmethod(DocumentProcessorServiceClient.parse_processor_path) + processor_type_path = staticmethod(DocumentProcessorServiceClient.processor_type_path) + parse_processor_type_path = staticmethod(DocumentProcessorServiceClient.parse_processor_type_path) + processor_version_path = staticmethod(DocumentProcessorServiceClient.processor_version_path) + parse_processor_version_path = staticmethod(DocumentProcessorServiceClient.parse_processor_version_path) + common_billing_account_path = staticmethod(DocumentProcessorServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentProcessorServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentProcessorServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentProcessorServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentProcessorServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentProcessorServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentProcessorServiceClient.common_project_path) + parse_common_project_path = staticmethod(DocumentProcessorServiceClient.parse_common_project_path) + common_location_path = staticmethod(DocumentProcessorServiceClient.common_location_path) + parse_common_location_path = staticmethod(DocumentProcessorServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceAsyncClient: The constructed client. + """ + return DocumentProcessorServiceClient.from_service_account_info.__func__(DocumentProcessorServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceAsyncClient: The constructed client. + """ + return DocumentProcessorServiceClient.from_service_account_file.__func__(DocumentProcessorServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DocumentProcessorServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DocumentProcessorServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentProcessorServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentProcessorServiceClient).get_transport_class, type(DocumentProcessorServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document processor service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DocumentProcessorServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DocumentProcessorServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def process_document(self, + request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.ProcessResponse: + r"""Processes a single document. + + .. 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_v1 + + async def sample_process_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = await client.process_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.ProcessRequest, dict]]): + The request object. Request message for the process + document method. + name (:class:`str`): + Required. The resource name of the + [Processor][google.cloud.documentai.v1.Processor] or + [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] + to use for processing. If a + [Processor][google.cloud.documentai.v1.Processor] is + specified, the server will use its [default + version][google.cloud.documentai.v1.Processor.default_processor_version]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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_v1.types.ProcessResponse: + Response message for the process + document 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([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.ProcessRequest(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.process_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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 batch_process_documents(self, + request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + .. 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_v1 + + async def sample_batch_process_documents(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.BatchProcessRequest, dict]]): + The request object. Request message for batch process + document method. + name (:class:`str`): + Required. The resource name of + [Processor][google.cloud.documentai.v1.Processor] or + [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1.types.BatchProcessResponse` + Response message for batch process document 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([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.BatchProcessRequest(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.batch_process_documents, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.BatchProcessResponse, + metadata_type=document_processor_service.BatchProcessMetadata, + ) + + # Done; return the response. + return response + + async def fetch_processor_types(self, + request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.FetchProcessorTypesResponse: + r"""Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + .. 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_v1 + + async def sample_fetch_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.fetch_processor_types(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.FetchProcessorTypesRequest, dict]]): + The request object. Request message for fetch processor + types. + parent (:class:`str`): + Required. The project of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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_v1.types.FetchProcessorTypesResponse: + Response message for fetch processor + types. + + """ + # 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.FetchProcessorTypesRequest(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.fetch_processor_types, + 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, + ) + + # Done; return the response. + return response + + async def list_processor_types(self, + request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorTypesAsyncPager: + r"""Lists the processor types that exist. + + .. 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_v1 + + async def sample_list_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorTypesRequest, dict]]): + The request object. Request message for list processor + types. + parent (:class:`str`): + Required. The location of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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_v1.services.document_processor_service.pagers.ListProcessorTypesAsyncPager: + Response message for list processor + types. + 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.ListProcessorTypesRequest(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_processor_types, + 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.ListProcessorTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_processor_type(self, + request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor_type.ProcessorType: + r"""Gets a processor type detail. + + .. 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_v1 + + async def sample_get_processor_type(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_type(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorTypeRequest, dict]]): + The request object. Request message for get processor. + name (:class:`str`): + Required. The processor type resource + name. + + 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_v1.types.ProcessorType: + A processor type is responsible for + performing a certain document + understanding task on a certain type of + document. + + """ + # 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.GetProcessorTypeRequest(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_processor_type, + 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_processors(self, + request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsAsyncPager: + r"""Lists all processors which belong to this project. + + .. 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_v1 + + async def sample_list_processors(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorsRequest, dict]]): + The request object. Request message for list all + processors belongs to a project. + parent (:class:`str`): + Required. The parent (project and location) which owns + this collection of Processors. Format: + ``projects/{project}/locations/{location}`` + + 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_v1.services.document_processor_service.pagers.ListProcessorsAsyncPager: + Response message for list processors. + 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.ListProcessorsRequest(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_processors, + 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.ListProcessorsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_processor(self, + request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.Processor: + r"""Gets a processor detail. + + .. 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_v1 + + async def sample_get_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorRequest, dict]]): + The request object. Request message for get processor. + name (:class:`str`): + Required. The processor resource + name. + + 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_v1.types.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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.GetProcessorRequest(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_processor, + 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 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_train_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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_v1.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_v1.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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.ProcessorVersion: + r"""Gets a processor version detail. + + .. 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_v1 + + async def sample_get_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorVersionRequest, dict]]): + The request object. Request message for get processor + version. + name (:class:`str`): + Required. The processor resource + name. + + 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_v1.types.ProcessorVersion: + A processor version is an + implementation of a processor. Each + processor can have multiple versions, + pre-trained by Google internally or + up-trained by the customer. At a time, a + processor can only have one default + version version. So the processor's + behavior (when processing documents) is + defined by a default version + + """ + # 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.GetProcessorVersionRequest(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_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(( + ("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_processor_versions(self, + request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorVersionsAsyncPager: + r"""Lists all versions of a processor. + + .. 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_v1 + + async def sample_list_processor_versions(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorVersionsRequest, dict]]): + The request object. Request message for list all + processor versions belongs to a processor. + parent (:class:`str`): + Required. The parent (project, location and processor) + to list all versions. 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. + 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_v1.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager: + Response message for list processors. + 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.ListProcessorVersionsRequest(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_processor_versions, + 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.ListProcessorVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_processor_version(self, + request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the processor version, all artifacts under + the processor version will be deleted. + + .. 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_v1 + + async def sample_delete_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_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_v1.types.DeleteProcessorVersionRequest, dict]]): + The request object. Request message for the delete + processor version method. + name (:class:`str`): + Required. The processor version + resource name to be deleted. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorVersionRequest(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.delete_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(( + ("name", request.name), + )), + ) + + # 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, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def deploy_processor_version(self, + request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys the 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_v1 + + async def sample_deploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_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_v1.types.DeployProcessorVersionRequest, dict]]): + The request object. Request message for the deploy + processor version method. + name (:class:`str`): + Required. The processor version + resource name to be deployed. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1.types.DeployProcessorVersionResponse` + Response message for the deploy processor version + 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([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.DeployProcessorVersionRequest(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.deploy_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(( + ("name", request.name), + )), + ) + + # 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.DeployProcessorVersionResponse, + metadata_type=document_processor_service.DeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def undeploy_processor_version(self, + request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Undeploys the 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_v1 + + async def sample_undeploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_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_v1.types.UndeployProcessorVersionRequest, dict]]): + The request object. Request message for the undeploy + processor version method. + name (:class:`str`): + Required. The processor version + resource name to be undeployed. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1.types.UndeployProcessorVersionResponse` + Response message for the undeploy processor version + 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([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.UndeployProcessorVersionRequest(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.undeploy_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(( + ("name", request.name), + )), + ) + + # 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.UndeployProcessorVersionResponse, + metadata_type=document_processor_service.UndeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def create_processor(self, + request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[gcd_processor.Processor] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_processor.Processor: + r"""Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + .. 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_v1 + + async def sample_create_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.CreateProcessorRequest, dict]]): + The request object. Request message for create a + processor. Notice this request is sent to a regionalized + backend service, and if the processor type is not + available on that region, the creation will fail. + parent (:class:`str`): + Required. The parent (project and location) under which + to create the processor. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (:class:`google.cloud.documentai_v1.types.Processor`): + Required. The processor to be created, requires + [processor_type] and [display_name] to be set. Also, the + processor is under CMEK if CMEK fields are set. + + This corresponds to the ``processor`` 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_v1.types.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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]) + 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.CreateProcessorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_processor, + 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, + ) + + # Done; return the response. + return response + + async def delete_processor(self, + request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + .. 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_v1 + + async def sample_delete_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.DeleteProcessorRequest, dict]]): + The request object. Request message for the delete + processor method. + name (:class:`str`): + Required. The processor resource name + to be deleted. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorRequest(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.delete_processor, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorMetadata, + ) + + # Done; return the response. + return response + + async def enable_processor(self, + request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Enables a processor + + .. 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_v1 + + async def sample_enable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.EnableProcessorRequest, dict]]): + The request object. Request message for the enable + processor method. + 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_v1.types.EnableProcessorResponse` Response message for the enable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + request = document_processor_service.EnableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.enable_processor, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.EnableProcessorResponse, + metadata_type=document_processor_service.EnableProcessorMetadata, + ) + + # Done; return the response. + return response + + async def disable_processor(self, + request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Disables a processor + + .. 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_v1 + + async def sample_disable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.DisableProcessorRequest, dict]]): + The request object. Request message for the disable + processor method. + 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_v1.types.DisableProcessorResponse` Response message for the disable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + request = document_processor_service.DisableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.disable_processor, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.DisableProcessorResponse, + metadata_type=document_processor_service.DisableProcessorMetadata, + ) + + # Done; return the response. + return response + + async def set_default_processor_version(self, + request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Set the default (active) version of a + [Processor][google.cloud.documentai.v1.Processor] that will be + used in + [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. + + .. 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_v1 + + async def sample_set_default_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_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_v1.types.SetDefaultProcessorVersionRequest, dict]]): + The request object. Request message for the set default + processor version method. + 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_v1.types.SetDefaultProcessorVersionResponse` + Response message for set default processor version + method. + + """ + # Create or coerce a protobuf request object. + request = document_processor_service.SetDefaultProcessorVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_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", request.processor), + )), + ) + + # 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.SetDefaultProcessorVersionResponse, + metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def review_document(self, + request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, + *, + human_review_config: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Send a document for Human Review. The input document + should be processed by the specified processor. + + .. 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_v1 + + async def sample_review_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1.types.ReviewDocumentRequest, dict]]): + The request object. Request message for review document + method. + human_review_config (:class:`str`): + Required. The resource name of the + HumanReviewConfig that the document will + be reviewed with. + + This corresponds to the ``human_review_config`` 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_v1.types.ReviewDocumentResponse` + Response message for review document 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([human_review_config]) + 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.ReviewDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if human_review_config is not None: + request.human_review_config = human_review_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.review_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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(( + ("human_review_config", request.human_review_config), + )), + ) + + # 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.ReviewDocumentResponse, + metadata_type=document_processor_service.ReviewDocumentOperationMetadata, + ) + + # 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_get_evaluation(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.types.GetEvaluationRequest, dict]]): + The request object. Retrieves a specific Evaluation. + name (:class:`str`): + Required. The resource name of the + [Evaluation][google.cloud.documentai.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_list_evaluations(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + 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: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + 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 cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + 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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + 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 __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentProcessorServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py new file mode 100644 index 00000000..1418ef7a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py @@ -0,0 +1,3196 @@ +# -*- 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 collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.documentai_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.documentai_v1.services.document_processor_service import pagers +from google.cloud.documentai_v1.types import document +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import document_schema +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentProcessorServiceGrpcTransport +from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport +from .transports.rest import DocumentProcessorServiceRestTransport + + +class DocumentProcessorServiceClientMeta(type): + """Metaclass for the DocumentProcessorService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] + _transport_registry["grpc"] = DocumentProcessorServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentProcessorServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DocumentProcessorServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DocumentProcessorServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DocumentProcessorServiceClient(metaclass=DocumentProcessorServiceClientMeta): + """Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "documentai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DocumentProcessorServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentProcessorServiceTransport: The transport used by the client + instance. + """ + 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,location: str,processor: str,) -> str: + """Returns a fully-qualified human_review_config string.""" + return "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) + + @staticmethod + def parse_human_review_config_path(path: str) -> Dict[str,str]: + """Parses a human_review_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/humanReviewConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_path(project: str,location: str,processor: str,) -> str: + """Returns a fully-qualified processor string.""" + return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + + @staticmethod + def parse_processor_path(path: str) -> Dict[str,str]: + """Parses a processor path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_type_path(project: str,location: str,processor_type: str,) -> str: + """Returns a fully-qualified processor_type string.""" + return "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) + + @staticmethod + def parse_processor_type_path(path: str) -> Dict[str,str]: + """Parses a processor_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processorTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_version_path(project: str,location: str,processor: str,processor_version: str,) -> str: + """Returns a fully-qualified processor_version string.""" + return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) + + @staticmethod + def parse_processor_version_path(path: str) -> Dict[str,str]: + """Parses a processor_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DocumentProcessorServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document processor service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, DocumentProcessorServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentProcessorServiceTransport): + # transport is a DocumentProcessorServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def process_document(self, + request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.ProcessResponse: + r"""Processes a single document. + + .. 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_v1 + + def sample_process_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = client.process_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.ProcessRequest, dict]): + The request object. Request message for the process + document method. + name (str): + Required. The resource name of the + [Processor][google.cloud.documentai.v1.Processor] or + [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] + to use for processing. If a + [Processor][google.cloud.documentai.v1.Processor] is + specified, the server will use its [default + version][google.cloud.documentai.v1.Processor.default_processor_version]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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_v1.types.ProcessResponse: + Response message for the process + document 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([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.ProcessRequest. + # 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.ProcessRequest): + request = document_processor_service.ProcessRequest(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.process_document] + + # 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 batch_process_documents(self, + request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + .. 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_v1 + + def sample_batch_process_documents(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.BatchProcessRequest, dict]): + The request object. Request message for batch process + document method. + name (str): + Required. The resource name of + [Processor][google.cloud.documentai.v1.Processor] or + [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1.types.BatchProcessResponse` + Response message for batch process document 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([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.BatchProcessRequest. + # 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.BatchProcessRequest): + request = document_processor_service.BatchProcessRequest(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.batch_process_documents] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.BatchProcessResponse, + metadata_type=document_processor_service.BatchProcessMetadata, + ) + + # Done; return the response. + return response + + def fetch_processor_types(self, + request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.FetchProcessorTypesResponse: + r"""Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + .. 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_v1 + + def sample_fetch_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = client.fetch_processor_types(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.FetchProcessorTypesRequest, dict]): + The request object. Request message for fetch processor + types. + parent (str): + Required. The project of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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_v1.types.FetchProcessorTypesResponse: + Response message for fetch processor + types. + + """ + # 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.FetchProcessorTypesRequest. + # 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.FetchProcessorTypesRequest): + request = document_processor_service.FetchProcessorTypesRequest(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.fetch_processor_types] + + # 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, + ) + + # Done; return the response. + return response + + def list_processor_types(self, + request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorTypesPager: + r"""Lists the processor types that exist. + + .. 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_v1 + + def sample_list_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.ListProcessorTypesRequest, dict]): + The request object. Request message for list processor + types. + parent (str): + Required. The location of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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_v1.services.document_processor_service.pagers.ListProcessorTypesPager: + Response message for list processor + types. + 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.ListProcessorTypesRequest. + # 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.ListProcessorTypesRequest): + request = document_processor_service.ListProcessorTypesRequest(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_processor_types] + + # 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.ListProcessorTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_processor_type(self, + request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor_type.ProcessorType: + r"""Gets a processor type detail. + + .. 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_v1 + + def sample_get_processor_type(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_type(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.GetProcessorTypeRequest, dict]): + The request object. Request message for get processor. + name (str): + Required. The processor type resource + name. + + 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_v1.types.ProcessorType: + A processor type is responsible for + performing a certain document + understanding task on a certain type of + document. + + """ + # 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.GetProcessorTypeRequest. + # 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.GetProcessorTypeRequest): + request = document_processor_service.GetProcessorTypeRequest(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_processor_type] + + # 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_processors(self, + request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsPager: + r"""Lists all processors which belong to this project. + + .. 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_v1 + + def sample_list_processors(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.ListProcessorsRequest, dict]): + The request object. Request message for list all + processors belongs to a project. + parent (str): + Required. The parent (project and location) which owns + this collection of Processors. Format: + ``projects/{project}/locations/{location}`` + + 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_v1.services.document_processor_service.pagers.ListProcessorsPager: + Response message for list processors. + 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.ListProcessorsRequest. + # 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.ListProcessorsRequest): + request = document_processor_service.ListProcessorsRequest(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_processors] + + # 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.ListProcessorsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_processor(self, + request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.Processor: + r"""Gets a processor detail. + + .. 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_v1 + + def sample_get_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.GetProcessorRequest, dict]): + The request object. Request message for get processor. + name (str): + Required. The processor resource + name. + + 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_v1.types.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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.GetProcessorRequest. + # 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.GetProcessorRequest): + request = document_processor_service.GetProcessorRequest(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_processor] + + # 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 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_train_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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_v1.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_v1.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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.ProcessorVersion: + r"""Gets a processor version detail. + + .. 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_v1 + + def sample_get_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.GetProcessorVersionRequest, dict]): + The request object. Request message for get processor + version. + name (str): + Required. The processor resource + name. + + 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_v1.types.ProcessorVersion: + A processor version is an + implementation of a processor. Each + processor can have multiple versions, + pre-trained by Google internally or + up-trained by the customer. At a time, a + processor can only have one default + version version. So the processor's + behavior (when processing documents) is + defined by a default version + + """ + # 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.GetProcessorVersionRequest. + # 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.GetProcessorVersionRequest): + request = document_processor_service.GetProcessorVersionRequest(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_processor_version] + + # 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_processor_versions(self, + request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorVersionsPager: + r"""Lists all versions of a processor. + + .. 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_v1 + + def sample_list_processor_versions(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.ListProcessorVersionsRequest, dict]): + The request object. Request message for list all + processor versions belongs to a processor. + parent (str): + Required. The parent (project, location and processor) + to list all versions. 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. + 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_v1.services.document_processor_service.pagers.ListProcessorVersionsPager: + Response message for list processors. + 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.ListProcessorVersionsRequest. + # 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.ListProcessorVersionsRequest): + request = document_processor_service.ListProcessorVersionsRequest(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_processor_versions] + + # 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.ListProcessorVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_processor_version(self, + request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the processor version, all artifacts under + the processor version will be deleted. + + .. 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_v1 + + def sample_delete_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.DeleteProcessorVersionRequest, dict]): + The request object. Request message for the delete + processor version method. + name (str): + Required. The processor version + resource name to be deleted. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorVersionRequest. + # 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.DeleteProcessorVersionRequest): + request = document_processor_service.DeleteProcessorVersionRequest(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.delete_processor_version] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def deploy_processor_version(self, + request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deploys the 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_v1 + + def sample_deploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.DeployProcessorVersionRequest, dict]): + The request object. Request message for the deploy + processor version method. + name (str): + Required. The processor version + resource name to be deployed. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1.types.DeployProcessorVersionResponse` + Response message for the deploy processor version + 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([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.DeployProcessorVersionRequest. + # 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.DeployProcessorVersionRequest): + request = document_processor_service.DeployProcessorVersionRequest(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.deploy_processor_version] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.DeployProcessorVersionResponse, + metadata_type=document_processor_service.DeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def undeploy_processor_version(self, + request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Undeploys the 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_v1 + + def sample_undeploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.UndeployProcessorVersionRequest, dict]): + The request object. Request message for the undeploy + processor version method. + name (str): + Required. The processor version + resource name to be undeployed. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1.types.UndeployProcessorVersionResponse` + Response message for the undeploy processor version + 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([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.UndeployProcessorVersionRequest. + # 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.UndeployProcessorVersionRequest): + request = document_processor_service.UndeployProcessorVersionRequest(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.undeploy_processor_version] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.UndeployProcessorVersionResponse, + metadata_type=document_processor_service.UndeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def create_processor(self, + request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[gcd_processor.Processor] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_processor.Processor: + r"""Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + .. 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_v1 + + def sample_create_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.CreateProcessorRequest, dict]): + The request object. Request message for create a + processor. Notice this request is sent to a regionalized + backend service, and if the processor type is not + available on that region, the creation will fail. + parent (str): + Required. The parent (project and location) under which + to create the processor. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (google.cloud.documentai_v1.types.Processor): + Required. The processor to be created, requires + [processor_type] and [display_name] to be set. Also, the + processor is under CMEK if CMEK fields are set. + + This corresponds to the ``processor`` 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_v1.types.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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]) + 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.CreateProcessorRequest. + # 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.CreateProcessorRequest): + request = document_processor_service.CreateProcessorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_processor] + + # 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, + ) + + # Done; return the response. + return response + + def delete_processor(self, + request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + .. 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_v1 + + def sample_delete_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.DeleteProcessorRequest, dict]): + The request object. Request message for the delete + processor method. + name (str): + Required. The processor resource name + to be deleted. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorRequest. + # 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.DeleteProcessorRequest): + request = document_processor_service.DeleteProcessorRequest(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.delete_processor] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorMetadata, + ) + + # Done; return the response. + return response + + def enable_processor(self, + request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Enables a processor + + .. 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_v1 + + def sample_enable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.EnableProcessorRequest, dict]): + The request object. Request message for the enable + processor method. + 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_v1.types.EnableProcessorResponse` Response message for the enable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.EnableProcessorRequest. + # 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.EnableProcessorRequest): + request = document_processor_service.EnableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.enable_processor] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.EnableProcessorResponse, + metadata_type=document_processor_service.EnableProcessorMetadata, + ) + + # Done; return the response. + return response + + def disable_processor(self, + request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Disables a processor + + .. 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_v1 + + def sample_disable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.DisableProcessorRequest, dict]): + The request object. Request message for the disable + processor method. + 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_v1.types.DisableProcessorResponse` Response message for the disable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.DisableProcessorRequest. + # 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.DisableProcessorRequest): + request = document_processor_service.DisableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.disable_processor] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.DisableProcessorResponse, + metadata_type=document_processor_service.DisableProcessorMetadata, + ) + + # Done; return the response. + return response + + def set_default_processor_version(self, + request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Set the default (active) version of a + [Processor][google.cloud.documentai.v1.Processor] that will be + used in + [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. + + .. 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_v1 + + def sample_set_default_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest, dict]): + The request object. Request message for the set default + processor version method. + 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_v1.types.SetDefaultProcessorVersionResponse` + Response message for set default processor version + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.SetDefaultProcessorVersionRequest. + # 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.SetDefaultProcessorVersionRequest): + request = document_processor_service.SetDefaultProcessorVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_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", request.processor), + )), + ) + + # 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.SetDefaultProcessorVersionResponse, + metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def review_document(self, + request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, + *, + human_review_config: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Send a document for Human Review. The input document + should be processed by the specified processor. + + .. 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_v1 + + def sample_review_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.ReviewDocumentRequest, dict]): + The request object. Request message for review document + method. + human_review_config (str): + Required. The resource name of the + HumanReviewConfig that the document will + be reviewed with. + + This corresponds to the ``human_review_config`` 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_v1.types.ReviewDocumentResponse` + Response message for review document 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([human_review_config]) + 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.ReviewDocumentRequest. + # 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.ReviewDocumentRequest): + request = document_processor_service.ReviewDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if human_review_config is not None: + request.human_review_config = human_review_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.review_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("human_review_config", request.human_review_config), + )), + ) + + # 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.ReviewDocumentResponse, + metadata_type=document_processor_service.ReviewDocumentOperationMetadata, + ) + + # 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_get_evaluation(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.GetEvaluationRequest, dict]): + The request object. Retrieves a specific Evaluation. + name (str): + Required. The resource name of the + [Evaluation][google.cloud.documentai.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_list_evaluations(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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) -> "DocumentProcessorServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + 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: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + 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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentProcessorServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py new file mode 100644 index 00000000..beb09ba8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py @@ -0,0 +1,505 @@ +# -*- 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 Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor_type + + +class ListProcessorTypesPager: + """A pager for iterating through ``list_processor_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processor_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessorTypes`` requests and continue to iterate + through the ``processor_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` + 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.ListProcessorTypesResponse], + request: document_processor_service.ListProcessorTypesRequest, + response: document_processor_service.ListProcessorTypesResponse, + *, + 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_v1.types.ListProcessorTypesRequest): + The initial request object. + response (google.cloud.documentai_v1.types.ListProcessorTypesResponse): + 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: + 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[processor_type.ProcessorType]: + for page in self.pages: + yield from page.processor_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorTypesAsyncPager: + """A pager for iterating through ``list_processor_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processor_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessorTypes`` requests and continue to iterate + through the ``processor_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` + 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.ListProcessorTypesResponse]], + request: document_processor_service.ListProcessorTypesRequest, + response: document_processor_service.ListProcessorTypesResponse, + *, + 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_v1.types.ListProcessorTypesRequest): + The initial request object. + response (google.cloud.documentai_v1.types.ListProcessorTypesResponse): + 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: + 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[processor_type.ProcessorType]: + async def async_generator(): + async for page in self.pages: + for response in page.processor_types: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` + 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.ListProcessorsResponse], + request: document_processor_service.ListProcessorsRequest, + response: document_processor_service.ListProcessorsResponse, + *, + 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_v1.types.ListProcessorsRequest): + The initial request object. + response (google.cloud.documentai_v1.types.ListProcessorsResponse): + 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.ListProcessorsRequest(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.ListProcessorsResponse]: + 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[processor.Processor]: + for page in self.pages: + yield from page.processors + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsAsyncPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` + 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.ListProcessorsResponse]], + request: document_processor_service.ListProcessorsRequest, + response: document_processor_service.ListProcessorsResponse, + *, + 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_v1.types.ListProcessorsRequest): + The initial request object. + response (google.cloud.documentai_v1.types.ListProcessorsResponse): + 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.ListProcessorsRequest(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.ListProcessorsResponse]: + 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[processor.Processor]: + async def async_generator(): + async for page in self.pages: + for response in page.processors: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorVersionsPager: + """A pager for iterating through ``list_processor_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processor_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessorVersions`` requests and continue to iterate + through the ``processor_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` + 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.ListProcessorVersionsResponse], + request: document_processor_service.ListProcessorVersionsRequest, + response: document_processor_service.ListProcessorVersionsResponse, + *, + 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_v1.types.ListProcessorVersionsRequest): + The initial request object. + response (google.cloud.documentai_v1.types.ListProcessorVersionsResponse): + 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: + 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[processor.ProcessorVersion]: + for page in self.pages: + yield from page.processor_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorVersionsAsyncPager: + """A pager for iterating through ``list_processor_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processor_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessorVersions`` requests and continue to iterate + through the ``processor_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` + 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.ListProcessorVersionsResponse]], + request: document_processor_service.ListProcessorVersionsRequest, + response: document_processor_service.ListProcessorVersionsResponse, + *, + 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_v1.types.ListProcessorVersionsRequest): + The initial request object. + response (google.cloud.documentai_v1.types.ListProcessorVersionsResponse): + 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: + 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[processor.ProcessorVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.processor_versions: + yield response + + return 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_v1.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_v1.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_v1.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.documentai_v1.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_v1.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_v1.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_v1.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.documentai_v1.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/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py new file mode 100644 index 00000000..cb5f6e80 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- 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 collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentProcessorServiceTransport +from .grpc import DocumentProcessorServiceGrpcTransport +from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport +from .rest import DocumentProcessorServiceRestTransport +from .rest import DocumentProcessorServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] +_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DocumentProcessorServiceRestTransport + +__all__ = ( + 'DocumentProcessorServiceTransport', + 'DocumentProcessorServiceGrpcTransport', + 'DocumentProcessorServiceGrpcAsyncIOTransport', + 'DocumentProcessorServiceRestTransport', + 'DocumentProcessorServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py new file mode 100644 index 00000000..f2a2f426 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py @@ -0,0 +1,519 @@ +# -*- 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.documentai_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DocumentProcessorServiceTransport(abc.ABC): + """Abstract transport class for DocumentProcessorService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'documentai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.process_document: gapic_v1.method.wrap_method( + self.process_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.batch_process_documents: gapic_v1.method.wrap_method( + self.batch_process_documents, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.fetch_processor_types: gapic_v1.method.wrap_method( + self.fetch_processor_types, + default_timeout=None, + client_info=client_info, + ), + self.list_processor_types: gapic_v1.method.wrap_method( + self.list_processor_types, + default_timeout=None, + client_info=client_info, + ), + self.get_processor_type: gapic_v1.method.wrap_method( + self.get_processor_type, + default_timeout=None, + client_info=client_info, + ), + self.list_processors: gapic_v1.method.wrap_method( + self.list_processors, + default_timeout=None, + client_info=client_info, + ), + self.get_processor: gapic_v1.method.wrap_method( + self.get_processor, + 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, + client_info=client_info, + ), + self.list_processor_versions: gapic_v1.method.wrap_method( + self.list_processor_versions, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor_version: gapic_v1.method.wrap_method( + self.delete_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.deploy_processor_version: gapic_v1.method.wrap_method( + self.deploy_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_processor_version: gapic_v1.method.wrap_method( + self.undeploy_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.create_processor: gapic_v1.method.wrap_method( + self.create_processor, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor: gapic_v1.method.wrap_method( + self.delete_processor, + default_timeout=None, + client_info=client_info, + ), + self.enable_processor: gapic_v1.method.wrap_method( + self.enable_processor, + default_timeout=None, + client_info=client_info, + ), + self.disable_processor: gapic_v1.method.wrap_method( + self.disable_processor, + default_timeout=None, + client_info=client_info, + ), + self.set_default_processor_version: gapic_v1.method.wrap_method( + self.set_default_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.review_document: gapic_v1.method.wrap_method( + self.review_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + 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): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + Union[ + document_processor_service.ProcessResponse, + Awaitable[document_processor_service.ProcessResponse] + ]]: + raise NotImplementedError() + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + Union[ + document_processor_service.FetchProcessorTypesResponse, + Awaitable[document_processor_service.FetchProcessorTypesResponse] + ]]: + raise NotImplementedError() + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + Union[ + document_processor_service.ListProcessorTypesResponse, + Awaitable[document_processor_service.ListProcessorTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + Union[ + processor_type.ProcessorType, + Awaitable[processor_type.ProcessorType] + ]]: + raise NotImplementedError() + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + Union[ + document_processor_service.ListProcessorsResponse, + Awaitable[document_processor_service.ListProcessorsResponse] + ]]: + raise NotImplementedError() + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + Union[ + processor.Processor, + Awaitable[processor.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) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + Union[ + processor.ProcessorVersion, + Awaitable[processor.ProcessorVersion] + ]]: + raise NotImplementedError() + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + Union[ + document_processor_service.ListProcessorVersionsResponse, + Awaitable[document_processor_service.ListProcessorVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + Union[ + gcd_processor.Processor, + Awaitable[gcd_processor.Processor] + ]]: + raise NotImplementedError() + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DocumentProcessorServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py new file mode 100644 index 00000000..4b6370cc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py @@ -0,0 +1,945 @@ +# -*- 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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO + + +class DocumentProcessorServiceGrpcTransport(DocumentProcessorServiceTransport): + """gRPC backend transport for DocumentProcessorService. + + Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + document_processor_service.ProcessResponse]: + r"""Return a callable for the process document method over gRPC. + + Processes a single document. + + Returns: + Callable[[~.ProcessRequest], + ~.ProcessResponse]: + 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 'process_document' not in self._stubs: + self._stubs['process_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ProcessDocument', + request_serializer=document_processor_service.ProcessRequest.serialize, + response_deserializer=document_processor_service.ProcessResponse.deserialize, + ) + return self._stubs['process_document'] + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch process documents method over gRPC. + + LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + Returns: + Callable[[~.BatchProcessRequest], + ~.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 'batch_process_documents' not in self._stubs: + self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/BatchProcessDocuments', + request_serializer=document_processor_service.BatchProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_process_documents'] + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + document_processor_service.FetchProcessorTypesResponse]: + r"""Return a callable for the fetch processor types method over gRPC. + + Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + Returns: + Callable[[~.FetchProcessorTypesRequest], + ~.FetchProcessorTypesResponse]: + 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 'fetch_processor_types' not in self._stubs: + self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/FetchProcessorTypes', + request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, + ) + return self._stubs['fetch_processor_types'] + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + document_processor_service.ListProcessorTypesResponse]: + r"""Return a callable for the list processor types method over gRPC. + + Lists the processor types that exist. + + Returns: + Callable[[~.ListProcessorTypesRequest], + ~.ListProcessorTypesResponse]: + 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_processor_types' not in self._stubs: + self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorTypes', + request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, + ) + return self._stubs['list_processor_types'] + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + processor_type.ProcessorType]: + r"""Return a callable for the get processor type method over gRPC. + + Gets a processor type detail. + + Returns: + Callable[[~.GetProcessorTypeRequest], + ~.ProcessorType]: + 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_processor_type' not in self._stubs: + self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorType', + request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, + response_deserializer=processor_type.ProcessorType.deserialize, + ) + return self._stubs['get_processor_type'] + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + document_processor_service.ListProcessorsResponse]: + r"""Return a callable for the list processors method over gRPC. + + Lists all processors which belong to this project. + + Returns: + Callable[[~.ListProcessorsRequest], + ~.ListProcessorsResponse]: + 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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessors', + request_serializer=document_processor_service.ListProcessorsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + processor.Processor]: + r"""Return a callable for the get processor method over gRPC. + + Gets a processor detail. + + Returns: + Callable[[~.GetProcessorRequest], + ~.Processor]: + 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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessor', + request_serializer=document_processor_service.GetProcessorRequest.serialize, + response_deserializer=processor.Processor.deserialize, + ) + 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.v1.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) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + processor.ProcessorVersion]: + r"""Return a callable for the get processor version method over gRPC. + + Gets a processor version detail. + + Returns: + Callable[[~.GetProcessorVersionRequest], + ~.ProcessorVersion]: + 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_processor_version' not in self._stubs: + self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorVersion', + request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, + response_deserializer=processor.ProcessorVersion.deserialize, + ) + return self._stubs['get_processor_version'] + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + document_processor_service.ListProcessorVersionsResponse]: + r"""Return a callable for the list processor versions method over gRPC. + + Lists all versions of a processor. + + Returns: + Callable[[~.ListProcessorVersionsRequest], + ~.ListProcessorVersionsResponse]: + 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_processor_versions' not in self._stubs: + self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorVersions', + request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, + ) + return self._stubs['list_processor_versions'] + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete processor version method over gRPC. + + Deletes the processor version, all artifacts under + the processor version will be deleted. + + Returns: + Callable[[~.DeleteProcessorVersionRequest], + ~.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 'delete_processor_version' not in self._stubs: + self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessorVersion', + request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor_version'] + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the deploy processor version method over gRPC. + + Deploys the processor version. + + Returns: + Callable[[~.DeployProcessorVersionRequest], + ~.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 'deploy_processor_version' not in self._stubs: + self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DeployProcessorVersion', + request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_processor_version'] + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the undeploy processor version method over gRPC. + + Undeploys the processor version. + + Returns: + Callable[[~.UndeployProcessorVersionRequest], + ~.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 'undeploy_processor_version' not in self._stubs: + self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/UndeployProcessorVersion', + request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_processor_version'] + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + gcd_processor.Processor]: + r"""Return a callable for the create processor method over gRPC. + + Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + Returns: + Callable[[~.CreateProcessorRequest], + ~.Processor]: + 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 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/CreateProcessor', + request_serializer=document_processor_service.CreateProcessorRequest.serialize, + response_deserializer=gcd_processor.Processor.deserialize, + ) + return self._stubs['create_processor'] + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + ~.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 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessor', + request_serializer=document_processor_service.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the enable processor method over gRPC. + + Enables a processor + + Returns: + Callable[[~.EnableProcessorRequest], + ~.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 'enable_processor' not in self._stubs: + self._stubs['enable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/EnableProcessor', + request_serializer=document_processor_service.EnableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['enable_processor'] + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the disable processor method over gRPC. + + Disables a processor + + Returns: + Callable[[~.DisableProcessorRequest], + ~.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 'disable_processor' not in self._stubs: + self._stubs['disable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DisableProcessor', + request_serializer=document_processor_service.DisableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['disable_processor'] + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the set default processor version method over gRPC. + + Set the default (active) version of a + [Processor][google.cloud.documentai.v1.Processor] that will be + used in + [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. + + Returns: + Callable[[~.SetDefaultProcessorVersionRequest], + ~.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 'set_default_processor_version' not in self._stubs: + self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/SetDefaultProcessorVersion', + request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_default_processor_version'] + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the review document method over gRPC. + + Send a document for Human Review. The input document + should be processed by the specified processor. + + Returns: + Callable[[~.ReviewDocumentRequest], + ~.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 'review_document' not in self._stubs: + self._stubs['review_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ReviewDocument', + request_serializer=document_processor_service.ReviewDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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.v1.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.v1.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.v1.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() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DocumentProcessorServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..25aa77d2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py @@ -0,0 +1,944 @@ +# -*- 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. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentProcessorServiceGrpcTransport + + +class DocumentProcessorServiceGrpcAsyncIOTransport(DocumentProcessorServiceTransport): + """gRPC AsyncIO backend transport for DocumentProcessorService. + + Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + Awaitable[document_processor_service.ProcessResponse]]: + r"""Return a callable for the process document method over gRPC. + + Processes a single document. + + Returns: + Callable[[~.ProcessRequest], + Awaitable[~.ProcessResponse]]: + 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 'process_document' not in self._stubs: + self._stubs['process_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ProcessDocument', + request_serializer=document_processor_service.ProcessRequest.serialize, + response_deserializer=document_processor_service.ProcessResponse.deserialize, + ) + return self._stubs['process_document'] + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch process documents method over gRPC. + + LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + Returns: + Callable[[~.BatchProcessRequest], + 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 'batch_process_documents' not in self._stubs: + self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/BatchProcessDocuments', + request_serializer=document_processor_service.BatchProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_process_documents'] + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + Awaitable[document_processor_service.FetchProcessorTypesResponse]]: + r"""Return a callable for the fetch processor types method over gRPC. + + Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + Returns: + Callable[[~.FetchProcessorTypesRequest], + Awaitable[~.FetchProcessorTypesResponse]]: + 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 'fetch_processor_types' not in self._stubs: + self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/FetchProcessorTypes', + request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, + ) + return self._stubs['fetch_processor_types'] + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + Awaitable[document_processor_service.ListProcessorTypesResponse]]: + r"""Return a callable for the list processor types method over gRPC. + + Lists the processor types that exist. + + Returns: + Callable[[~.ListProcessorTypesRequest], + Awaitable[~.ListProcessorTypesResponse]]: + 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_processor_types' not in self._stubs: + self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorTypes', + request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, + ) + return self._stubs['list_processor_types'] + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + Awaitable[processor_type.ProcessorType]]: + r"""Return a callable for the get processor type method over gRPC. + + Gets a processor type detail. + + Returns: + Callable[[~.GetProcessorTypeRequest], + Awaitable[~.ProcessorType]]: + 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_processor_type' not in self._stubs: + self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorType', + request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, + response_deserializer=processor_type.ProcessorType.deserialize, + ) + return self._stubs['get_processor_type'] + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + Awaitable[document_processor_service.ListProcessorsResponse]]: + r"""Return a callable for the list processors method over gRPC. + + Lists all processors which belong to this project. + + Returns: + Callable[[~.ListProcessorsRequest], + Awaitable[~.ListProcessorsResponse]]: + 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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessors', + request_serializer=document_processor_service.ListProcessorsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + Awaitable[processor.Processor]]: + r"""Return a callable for the get processor method over gRPC. + + Gets a processor detail. + + Returns: + Callable[[~.GetProcessorRequest], + Awaitable[~.Processor]]: + 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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessor', + request_serializer=document_processor_service.GetProcessorRequest.serialize, + response_deserializer=processor.Processor.deserialize, + ) + 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.v1.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) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + Awaitable[processor.ProcessorVersion]]: + r"""Return a callable for the get processor version method over gRPC. + + Gets a processor version detail. + + Returns: + Callable[[~.GetProcessorVersionRequest], + Awaitable[~.ProcessorVersion]]: + 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_processor_version' not in self._stubs: + self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorVersion', + request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, + response_deserializer=processor.ProcessorVersion.deserialize, + ) + return self._stubs['get_processor_version'] + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + Awaitable[document_processor_service.ListProcessorVersionsResponse]]: + r"""Return a callable for the list processor versions method over gRPC. + + Lists all versions of a processor. + + Returns: + Callable[[~.ListProcessorVersionsRequest], + Awaitable[~.ListProcessorVersionsResponse]]: + 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_processor_versions' not in self._stubs: + self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorVersions', + request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, + ) + return self._stubs['list_processor_versions'] + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete processor version method over gRPC. + + Deletes the processor version, all artifacts under + the processor version will be deleted. + + Returns: + Callable[[~.DeleteProcessorVersionRequest], + 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 'delete_processor_version' not in self._stubs: + self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessorVersion', + request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor_version'] + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the deploy processor version method over gRPC. + + Deploys the processor version. + + Returns: + Callable[[~.DeployProcessorVersionRequest], + 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 'deploy_processor_version' not in self._stubs: + self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DeployProcessorVersion', + request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_processor_version'] + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the undeploy processor version method over gRPC. + + Undeploys the processor version. + + Returns: + Callable[[~.UndeployProcessorVersionRequest], + 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 'undeploy_processor_version' not in self._stubs: + self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/UndeployProcessorVersion', + request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_processor_version'] + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + Awaitable[gcd_processor.Processor]]: + r"""Return a callable for the create processor method over gRPC. + + Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + Returns: + Callable[[~.CreateProcessorRequest], + Awaitable[~.Processor]]: + 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 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/CreateProcessor', + request_serializer=document_processor_service.CreateProcessorRequest.serialize, + response_deserializer=gcd_processor.Processor.deserialize, + ) + return self._stubs['create_processor'] + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + 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 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessor', + request_serializer=document_processor_service.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the enable processor method over gRPC. + + Enables a processor + + Returns: + Callable[[~.EnableProcessorRequest], + 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 'enable_processor' not in self._stubs: + self._stubs['enable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/EnableProcessor', + request_serializer=document_processor_service.EnableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['enable_processor'] + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the disable processor method over gRPC. + + Disables a processor + + Returns: + Callable[[~.DisableProcessorRequest], + 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 'disable_processor' not in self._stubs: + self._stubs['disable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/DisableProcessor', + request_serializer=document_processor_service.DisableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['disable_processor'] + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set default processor version method over gRPC. + + Set the default (active) version of a + [Processor][google.cloud.documentai.v1.Processor] that will be + used in + [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. + + Returns: + Callable[[~.SetDefaultProcessorVersionRequest], + 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 'set_default_processor_version' not in self._stubs: + self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/SetDefaultProcessorVersion', + request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_default_processor_version'] + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the review document method over gRPC. + + Send a document for Human Review. The input document + should be processed by the specified processor. + + Returns: + Callable[[~.ReviewDocumentRequest], + 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 'review_document' not in self._stubs: + self._stubs['review_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1.DocumentProcessorService/ReviewDocument', + request_serializer=document_processor_service.ReviewDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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.v1.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.v1.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.v1.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() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'DocumentProcessorServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py new file mode 100644 index 00000000..383660ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py @@ -0,0 +1,3288 @@ +# -*- 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 google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.longrunning import operations_pb2 # type: ignore + +from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DocumentProcessorServiceRestInterceptor: + """Interceptor for DocumentProcessorService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the DocumentProcessorServiceRestTransport. + + .. code-block:: python + class MyCustomDocumentProcessorServiceInterceptor(DocumentProcessorServiceRestInterceptor): + def pre_batch_process_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_process_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_deploy_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_deploy_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_disable_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_enable_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_evaluate_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_evaluate_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_processor_types(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_processor_types(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor_type(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processor_types(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processor_types(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processor_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processor_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_process_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_process_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_review_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_review_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_default_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_default_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_train_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_train_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undeploy_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undeploy_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DocumentProcessorServiceRestTransport(interceptor=MyCustomDocumentProcessorServiceInterceptor()) + client = DocumentProcessorServiceClient(transport=transport) + + + """ + def pre_batch_process_documents(self, request: document_processor_service.BatchProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.BatchProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_process_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_batch_process_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_process_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_create_processor(self, request: document_processor_service.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.CreateProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_create_processor(self, response: gcd_processor.Processor) -> gcd_processor.Processor: + """Post-rpc interceptor for create_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_delete_processor(self, request: document_processor_service.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_delete_processor_version(self, request: document_processor_service.DeleteProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_delete_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_deploy_processor_version(self, request: document_processor_service.DeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for deploy_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_deploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for deploy_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_disable_processor(self, request: document_processor_service.DisableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DisableProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for disable_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_disable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for disable_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_enable_processor(self, request: document_processor_service.EnableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EnableProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for enable_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_enable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for enable_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_evaluate_processor_version(self, request: document_processor_service.EvaluateProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EvaluateProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for evaluate_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_evaluate_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for evaluate_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_fetch_processor_types(self, request: document_processor_service.FetchProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.FetchProcessorTypesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for fetch_processor_types + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_fetch_processor_types(self, response: document_processor_service.FetchProcessorTypesResponse) -> document_processor_service.FetchProcessorTypesResponse: + """Post-rpc interceptor for fetch_processor_types + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_evaluation(self, request: document_processor_service.GetEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_evaluation(self, response: evaluation.Evaluation) -> evaluation.Evaluation: + """Post-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_processor(self, request: document_processor_service.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_processor(self, response: processor.Processor) -> processor.Processor: + """Post-rpc interceptor for get_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_processor_type(self, request: document_processor_service.GetProcessorTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorTypeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_processor_type(self, response: processor_type.ProcessorType) -> processor_type.ProcessorType: + """Post-rpc interceptor for get_processor_type + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_processor_version(self, request: document_processor_service.GetProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_processor_version(self, response: processor.ProcessorVersion) -> processor.ProcessorVersion: + """Post-rpc interceptor for get_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_evaluations(self, request: document_processor_service.ListEvaluationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_evaluations(self, response: document_processor_service.ListEvaluationsResponse) -> document_processor_service.ListEvaluationsResponse: + """Post-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_processors(self, request: document_processor_service.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_processors(self, response: document_processor_service.ListProcessorsResponse) -> document_processor_service.ListProcessorsResponse: + """Post-rpc interceptor for list_processors + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_processor_types(self, request: document_processor_service.ListProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorTypesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processor_types + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_processor_types(self, response: document_processor_service.ListProcessorTypesResponse) -> document_processor_service.ListProcessorTypesResponse: + """Post-rpc interceptor for list_processor_types + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_processor_versions(self, request: document_processor_service.ListProcessorVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorVersionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processor_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_processor_versions(self, response: document_processor_service.ListProcessorVersionsResponse) -> document_processor_service.ListProcessorVersionsResponse: + """Post-rpc interceptor for list_processor_versions + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_process_document(self, request: document_processor_service.ProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for process_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_process_document(self, response: document_processor_service.ProcessResponse) -> document_processor_service.ProcessResponse: + """Post-rpc interceptor for process_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_review_document(self, request: document_processor_service.ReviewDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ReviewDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for review_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_review_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for review_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_set_default_processor_version(self, request: document_processor_service.SetDefaultProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.SetDefaultProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_default_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_set_default_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for set_default_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_train_processor_version(self, request: document_processor_service.TrainProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.TrainProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for train_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_train_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for train_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_undeploy_processor_version(self, request: document_processor_service.UndeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.UndeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undeploy_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_undeploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for undeploy_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + + def pre_get_location(self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.Location: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_location(self, response: locations_pb2.GetLocationRequest) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_locations(self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.ListLocationsResponse: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_locations(self, response: locations_pb2.ListLocationsRequest) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation(self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]]) -> None: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_cancel_operation(self, response: operations_pb2.CancelOperationRequest) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_operation(self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_operation(self, response: operations_pb2.GetOperationRequest) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_operations(self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.ListOperationsResponse: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_operations(self, response: operations_pb2.ListOperationsRequest) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DocumentProcessorServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DocumentProcessorServiceRestInterceptor + + +class DocumentProcessorServiceRestTransport(DocumentProcessorServiceTransport): + """REST backend transport for DocumentProcessorService. + + Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[DocumentProcessorServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DocumentProcessorServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + }, + { + 'method': 'post', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations}', + }, + { + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _BatchProcessDocuments(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("BatchProcessDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.BatchProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch process documents method over HTTP. + + Args: + request (~.document_processor_service.BatchProcessRequest): + The request object. Request message for batch process + document method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}:batchProcess', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:batchProcess', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_process_documents(request, metadata) + pb_request = document_processor_service.BatchProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_process_documents(resp) + return resp + + class _CreateProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("CreateProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.CreateProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_processor.Processor: + r"""Call the create processor method over HTTP. + + Args: + request (~.document_processor_service.CreateProcessorRequest): + The request object. Request message for create a + processor. Notice this request is sent + to a regionalized backend service, and + if the processor type is not available + on that region, the creation will fail. + + 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: + ~.gcd_processor.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/processors', + 'body': 'processor', + }, + ] + request, metadata = self._interceptor.pre_create_processor(request, metadata) + pb_request = document_processor_service.CreateProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_processor.Processor() + pb_resp = gcd_processor.Processor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_processor(resp) + return resp + + class _DeleteProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DeleteProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DeleteProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete processor method over HTTP. + + Args: + request (~.document_processor_service.DeleteProcessorRequest): + The request object. Request message for the delete + processor method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_processor(request, metadata) + pb_request = document_processor_service.DeleteProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_processor(resp) + return resp + + class _DeleteProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DeleteProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DeleteProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete processor version method over HTTP. + + Args: + request (~.document_processor_service.DeleteProcessorVersionRequest): + The request object. Request message for the delete + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_processor_version(request, metadata) + pb_request = document_processor_service.DeleteProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_processor_version(resp) + return resp + + class _DeployProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DeployProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DeployProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the deploy processor version method over HTTP. + + Args: + request (~.document_processor_service.DeployProcessorVersionRequest): + The request object. Request message for the deploy + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_deploy_processor_version(request, metadata) + pb_request = document_processor_service.DeployProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_deploy_processor_version(resp) + return resp + + class _DisableProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DisableProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DisableProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the disable processor method over HTTP. + + Args: + request (~.document_processor_service.DisableProcessorRequest): + The request object. Request message for the disable + processor method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}:disable', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_disable_processor(request, metadata) + pb_request = document_processor_service.DisableProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_disable_processor(resp) + return resp + + class _EnableProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("EnableProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.EnableProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the enable processor method over HTTP. + + Args: + request (~.document_processor_service.EnableProcessorRequest): + The request object. Request message for the enable + processor method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}:enable', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_enable_processor(request, metadata) + pb_request = document_processor_service.EnableProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_enable_processor(resp) + return resp + + class _EvaluateProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("EvaluateProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.EvaluateProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the evaluate processor + version method over HTTP. + + Args: + request (~.document_processor_service.EvaluateProcessorVersionRequest): + The request object. Evaluates the given ProcessorVersion + against the supplied documents. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_evaluate_processor_version(request, metadata) + pb_request = document_processor_service.EvaluateProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_evaluate_processor_version(resp) + return resp + + class _FetchProcessorTypes(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("FetchProcessorTypes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.FetchProcessorTypesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.FetchProcessorTypesResponse: + r"""Call the fetch processor types method over HTTP. + + Args: + request (~.document_processor_service.FetchProcessorTypesRequest): + The request object. Request message for fetch processor + types. + + 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: + ~.document_processor_service.FetchProcessorTypesResponse: + Response message for fetch processor + types. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}:fetchProcessorTypes', + }, + ] + request, metadata = self._interceptor.pre_fetch_processor_types(request, metadata) + pb_request = document_processor_service.FetchProcessorTypesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.FetchProcessorTypesResponse() + pb_resp = document_processor_service.FetchProcessorTypesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_processor_types(resp) + return resp + + class _GetEvaluation(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetEvaluation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetEvaluationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> evaluation.Evaluation: + r"""Call the get evaluation method over HTTP. + + Args: + request (~.document_processor_service.GetEvaluationRequest): + The request object. Retrieves a specific Evaluation. + 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: + ~.evaluation.Evaluation: + An evaluation of a ProcessorVersion's + performance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_evaluation(request, metadata) + pb_request = document_processor_service.GetEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.Evaluation() + pb_resp = evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_evaluation(resp) + return resp + + class _GetProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> processor.Processor: + r"""Call the get processor method over HTTP. + + Args: + request (~.document_processor_service.GetProcessorRequest): + The request object. Request message for get processor. + 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: + ~.processor.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor(request, metadata) + pb_request = document_processor_service.GetProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = processor.Processor() + pb_resp = processor.Processor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor(resp) + return resp + + class _GetProcessorType(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetProcessorType") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetProcessorTypeRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> processor_type.ProcessorType: + r"""Call the get processor type method over HTTP. + + Args: + request (~.document_processor_service.GetProcessorTypeRequest): + The request object. Request message for get processor. + 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: + ~.processor_type.ProcessorType: + A processor type is responsible for + performing a certain document + understanding task on a certain type of + document. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/processorTypes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor_type(request, metadata) + pb_request = document_processor_service.GetProcessorTypeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = processor_type.ProcessorType() + pb_resp = processor_type.ProcessorType.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor_type(resp) + return resp + + class _GetProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> processor.ProcessorVersion: + r"""Call the get processor version method over HTTP. + + Args: + request (~.document_processor_service.GetProcessorVersionRequest): + The request object. Request message for get processor + version. + + 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: + ~.processor.ProcessorVersion: + A processor version is an + implementation of a processor. Each + processor can have multiple versions, + pre-trained by Google internally or + up-trained by the customer. At a time, a + processor can only have one default + version version. So the processor's + behavior (when processing documents) is + defined by a default version + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor_version(request, metadata) + pb_request = document_processor_service.GetProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = processor.ProcessorVersion() + pb_resp = processor.ProcessorVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor_version(resp) + return resp + + class _ListEvaluations(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListEvaluations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListEvaluationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListEvaluationsResponse: + r"""Call the list evaluations method over HTTP. + + Args: + request (~.document_processor_service.ListEvaluationsRequest): + The request object. Retrieves a list of evaluations for a + given ProcessorVersion. + + 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: + ~.document_processor_service.ListEvaluationsResponse: + The response from ListEvaluations. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations', + }, + ] + request, metadata = self._interceptor.pre_list_evaluations(request, metadata) + pb_request = document_processor_service.ListEvaluationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListEvaluationsResponse() + pb_resp = document_processor_service.ListEvaluationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_evaluations(resp) + return resp + + class _ListProcessors(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListProcessors") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListProcessorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListProcessorsResponse: + r"""Call the list processors method over HTTP. + + Args: + request (~.document_processor_service.ListProcessorsRequest): + The request object. Request message for list all + processors belongs to a project. + + 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: + ~.document_processor_service.ListProcessorsResponse: + Response message for list processors. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/processors', + }, + ] + request, metadata = self._interceptor.pre_list_processors(request, metadata) + pb_request = document_processor_service.ListProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListProcessorsResponse() + pb_resp = document_processor_service.ListProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processors(resp) + return resp + + class _ListProcessorTypes(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListProcessorTypes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListProcessorTypesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListProcessorTypesResponse: + r"""Call the list processor types method over HTTP. + + Args: + request (~.document_processor_service.ListProcessorTypesRequest): + The request object. Request message for list processor + types. + + 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: + ~.document_processor_service.ListProcessorTypesResponse: + Response message for list processor + types. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/processorTypes', + }, + ] + request, metadata = self._interceptor.pre_list_processor_types(request, metadata) + pb_request = document_processor_service.ListProcessorTypesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListProcessorTypesResponse() + pb_resp = document_processor_service.ListProcessorTypesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processor_types(resp) + return resp + + class _ListProcessorVersions(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListProcessorVersions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListProcessorVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListProcessorVersionsResponse: + r"""Call the list processor versions method over HTTP. + + Args: + request (~.document_processor_service.ListProcessorVersionsRequest): + The request object. Request message for list all + processor versions belongs to a + processor. + + 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: + ~.document_processor_service.ListProcessorVersionsResponse: + Response message for list processors. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/processors/*}/processorVersions', + }, + ] + request, metadata = self._interceptor.pre_list_processor_versions(request, metadata) + pb_request = document_processor_service.ListProcessorVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListProcessorVersionsResponse() + pb_resp = document_processor_service.ListProcessorVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processor_versions(resp) + return resp + + class _ProcessDocument(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ProcessDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ProcessResponse: + r"""Call the process document method over HTTP. + + Args: + request (~.document_processor_service.ProcessRequest): + The request object. Request message for the process + document method. + + 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: + ~.document_processor_service.ProcessResponse: + Response message for the process + document method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}:process', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:process', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_process_document(request, metadata) + pb_request = document_processor_service.ProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ProcessResponse() + pb_resp = document_processor_service.ProcessResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_process_document(resp) + return resp + + class _ReviewDocument(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ReviewDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ReviewDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the review document method over HTTP. + + Args: + request (~.document_processor_service.ReviewDocumentRequest): + The request object. Request message for review document + method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_review_document(request, metadata) + pb_request = document_processor_service.ReviewDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_review_document(resp) + return resp + + class _SetDefaultProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("SetDefaultProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.SetDefaultProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the set default processor + version method over HTTP. + + Args: + request (~.document_processor_service.SetDefaultProcessorVersionRequest): + The request object. Request message for the set default + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{processor=projects/*/locations/*/processors/*}:setDefaultProcessorVersion', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_default_processor_version(request, metadata) + pb_request = document_processor_service.SetDefaultProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_default_processor_version(resp) + return resp + + class _TrainProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("TrainProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.TrainProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the train processor version method over HTTP. + + Args: + request (~.document_processor_service.TrainProcessorVersionRequest): + The request object. Request message for the create + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_train_processor_version(request, metadata) + pb_request = document_processor_service.TrainProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_train_processor_version(resp) + return resp + + class _UndeployProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("UndeployProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.UndeployProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the undeploy processor + version method over HTTP. + + Args: + request (~.document_processor_service.UndeployProcessorVersionRequest): + The request object. Request message for the undeploy + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_undeploy_processor_version(request, metadata) + pb_request = document_processor_service.UndeployProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undeploy_processor_version(resp) + return resp + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchProcessDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + gcd_processor.Processor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DisableProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EnableProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def evaluate_processor_version(self) -> Callable[ + [document_processor_service.EvaluateProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EvaluateProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + document_processor_service.FetchProcessorTypesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchProcessorTypes(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation(self) -> Callable[ + [document_processor_service.GetEvaluationRequest], + evaluation.Evaluation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + processor.Processor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + processor_type.ProcessorType]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessorType(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor_version(self) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + processor.ProcessorVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluations(self) -> Callable[ + [document_processor_service.ListEvaluationsRequest], + document_processor_service.ListEvaluationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + document_processor_service.ListProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + document_processor_service.ListProcessorTypesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessorTypes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + document_processor_service.ListProcessorVersionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessorVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + document_processor_service.ProcessResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ProcessDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReviewDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetDefaultProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def train_processor_version(self) -> Callable[ + [document_processor_service.TrainProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TrainProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(DocumentProcessorServiceRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + 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: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(DocumentProcessorServiceRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + 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: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(DocumentProcessorServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + }, +{ + 'method': 'post', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(DocumentProcessorServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + 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: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(DocumentProcessorServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + 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: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations}', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DocumentProcessorServiceRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py new file mode 100644 index 00000000..b86d11cb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py @@ -0,0 +1,172 @@ +# -*- 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 .barcode import ( + Barcode, +) +from .document import ( + Document, +) +from .document_io import ( + BatchDocumentsInputConfig, + DocumentOutputConfig, + GcsDocument, + GcsDocuments, + GcsPrefix, + RawDocument, +) +from .document_processor_service import ( + BatchProcessMetadata, + BatchProcessRequest, + BatchProcessResponse, + CreateProcessorRequest, + DeleteProcessorMetadata, + DeleteProcessorRequest, + DeleteProcessorVersionMetadata, + DeleteProcessorVersionRequest, + DeployProcessorVersionMetadata, + DeployProcessorVersionRequest, + DeployProcessorVersionResponse, + DisableProcessorMetadata, + DisableProcessorRequest, + DisableProcessorResponse, + EnableProcessorMetadata, + EnableProcessorRequest, + EnableProcessorResponse, + EvaluateProcessorVersionMetadata, + EvaluateProcessorVersionRequest, + EvaluateProcessorVersionResponse, + FetchProcessorTypesRequest, + FetchProcessorTypesResponse, + GetEvaluationRequest, + GetProcessorRequest, + GetProcessorTypeRequest, + GetProcessorVersionRequest, + HumanReviewStatus, + ListEvaluationsRequest, + ListEvaluationsResponse, + ListProcessorsRequest, + ListProcessorsResponse, + ListProcessorTypesRequest, + ListProcessorTypesResponse, + ListProcessorVersionsRequest, + ListProcessorVersionsResponse, + ProcessRequest, + ProcessResponse, + ReviewDocumentOperationMetadata, + ReviewDocumentRequest, + ReviewDocumentResponse, + SetDefaultProcessorVersionMetadata, + SetDefaultProcessorVersionRequest, + SetDefaultProcessorVersionResponse, + TrainProcessorVersionMetadata, + TrainProcessorVersionRequest, + TrainProcessorVersionResponse, + UndeployProcessorVersionMetadata, + UndeployProcessorVersionRequest, + UndeployProcessorVersionResponse, +) +from .document_schema import ( + DocumentSchema, +) +from .evaluation import ( + Evaluation, + EvaluationReference, +) +from .geometry import ( + BoundingPoly, + NormalizedVertex, + Vertex, +) +from .operation_metadata import ( + CommonOperationMetadata, +) +from .processor import ( + Processor, + ProcessorVersion, +) +from .processor_type import ( + ProcessorType, +) + +__all__ = ( + 'Barcode', + 'Document', + 'BatchDocumentsInputConfig', + 'DocumentOutputConfig', + 'GcsDocument', + 'GcsDocuments', + 'GcsPrefix', + 'RawDocument', + 'BatchProcessMetadata', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'CreateProcessorRequest', + 'DeleteProcessorMetadata', + 'DeleteProcessorRequest', + 'DeleteProcessorVersionMetadata', + 'DeleteProcessorVersionRequest', + 'DeployProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DisableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'EnableProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EvaluateProcessorVersionMetadata', + 'EvaluateProcessorVersionRequest', + 'EvaluateProcessorVersionResponse', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetEvaluationRequest', + 'GetProcessorRequest', + 'GetProcessorTypeRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListEvaluationsRequest', + 'ListEvaluationsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'TrainProcessorVersionMetadata', + 'TrainProcessorVersionRequest', + 'TrainProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + 'Evaluation', + 'EvaluationReference', + 'BoundingPoly', + 'NormalizedVertex', + 'Vertex', + 'CommonOperationMetadata', + 'Processor', + 'ProcessorVersion', + 'ProcessorType', +) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py new file mode 100644 index 00000000..3e7ca5bd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py @@ -0,0 +1,85 @@ +# -*- 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 + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'Barcode', + }, +) + + +class Barcode(proto.Message): + r"""Encodes the detailed information of a barcode. + + 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. + 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. + raw_value (str): + Raw value encoded in the barcode. For example: + ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. + """ + + format_: str = proto.Field( + proto.STRING, + number=1, + ) + value_format: str = proto.Field( + proto.STRING, + number=2, + ) + raw_value: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py new file mode 100644 index 00000000..131d383f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py @@ -0,0 +1,1708 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.documentai_v1.types import barcode as gcd_barcode +from google.cloud.documentai_v1.types import geometry +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from google.type import money_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'Document', + }, +) + + +class Document(proto.Message): + r"""Document represents the canonical document resource in + Document AI. It is an interchange format that provides insights + into documents and allows for collaboration between users and + Document AI to iterate and optimize for quality. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Optional. Currently supports Google Cloud Storage URI of the + form ``gs://bucket_name/object_name``. Object versioning is + not supported. See `Google Cloud Storage Request + URIs `__ + for more info. + + This field is a member of `oneof`_ ``source``. + content (bytes): + Optional. Inline document content, represented as a stream + of bytes. Note: As with all ``bytes`` fields, protobuffers + use a pure binary representation, whereas JSON + representations use base64. + + This field is a member of `oneof`_ ``source``. + mime_type (str): + An IANA published MIME type (also referred to + as media type). For more information, see + https://www.iana.org/assignments/media-types/media-types.xhtml. + text (str): + Optional. UTF-8 encoded text in reading order + from the document. + text_styles (MutableSequence[google.cloud.documentai_v1.types.Document.Style]): + Styles for the + [Document.text][google.cloud.documentai.v1.Document.text]. + pages (MutableSequence[google.cloud.documentai_v1.types.Document.Page]): + Visual page layout for the + [Document][google.cloud.documentai.v1.Document]. + entities (MutableSequence[google.cloud.documentai_v1.types.Document.Entity]): + A list of entities detected on + [Document.text][google.cloud.documentai.v1.Document.text]. + For document shards, entities in this list may cross shard + boundaries. + entity_relations (MutableSequence[google.cloud.documentai_v1.types.Document.EntityRelation]): + Placeholder. Relationship among + [Document.entities][google.cloud.documentai.v1.Document.entities]. + text_changes (MutableSequence[google.cloud.documentai_v1.types.Document.TextChange]): + Placeholder. A list of text corrections made to + [Document.text][google.cloud.documentai.v1.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_v1.types.Document.ShardInfo): + Information about the sharding if this + document is sharded part of a larger document. + If the document is not sharded, this message is + not specified. + error (google.rpc.status_pb2.Status): + Any error that occurred while processing this + document. + revisions (MutableSequence[google.cloud.documentai_v1.types.Document.Revision]): + Placeholder. Revision history of this + document. + """ + + class ShardInfo(proto.Message): + r"""For a large document, sharding may be performed to produce + several document shards. Each document shard contains this field + to detail which shard it is. + + Attributes: + shard_index (int): + The 0-based index of this shard. + shard_count (int): + Total number of shards. + text_offset (int): + The index of the first character in + [Document.text][google.cloud.documentai.v1.Document.text] in + the overall document global text. + """ + + shard_index: int = proto.Field( + proto.INT64, + number=1, + ) + shard_count: int = proto.Field( + proto.INT64, + number=2, + ) + text_offset: int = proto.Field( + proto.INT64, + number=3, + ) + + class Style(proto.Message): + r"""Annotation for common text style attributes. This adheres to + CSS conventions as much as possible. + + Attributes: + text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): + Text anchor indexing into the + [Document.text][google.cloud.documentai.v1.Document.text]. + color (google.type.color_pb2.Color): + Text color. + background_color (google.type.color_pb2.Color): + Text background color. + font_weight (str): + Font weight. Possible values are normal, bold, bolder, and + lighter. https://www.w3schools.com/cssref/pr_font_weight.asp + text_style (str): + Text style. Possible values are normal, italic, and oblique. + https://www.w3schools.com/cssref/pr_font_font-style.asp + text_decoration (str): + Text decoration. Follows CSS standard. + https://www.w3schools.com/cssref/pr_text_text-decoration.asp + font_size (google.cloud.documentai_v1.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): + r"""Font size with unit. + + Attributes: + size (float): + Font size for the text. + unit (str): + Unit for the font size. Follows CSS naming + (in, px, pt, etc.). + """ + + size: float = proto.Field( + proto.FLOAT, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=2, + message=color_pb2.Color, + ) + background_color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=3, + message=color_pb2.Color, + ) + font_weight: str = proto.Field( + proto.STRING, + number=4, + ) + text_style: str = proto.Field( + proto.STRING, + number=5, + ) + text_decoration: str = proto.Field( + proto.STRING, + number=6, + ) + font_size: 'Document.Style.FontSize' = proto.Field( + 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.v1.Document]. + + Attributes: + page_number (int): + 1-based index for current + [Page][google.cloud.documentai.v1.Document.Page] in a parent + [Document][google.cloud.documentai.v1.Document]. Useful when + a page is taken out of a + [Document][google.cloud.documentai.v1.Document] for + individual processing. + image (google.cloud.documentai_v1.types.Document.Page.Image): + Rendered image for this page. This image is + preprocessed to remove any skew, rotation, and + distortions such that the annotation bounding + boxes can be upright and axis-aligned. + transforms (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Matrix]): + Transformation matrices that were applied to the original + document image to produce + [Page.image][google.cloud.documentai.v1.Document.Page.image]. + dimension (google.cloud.documentai_v1.types.Document.Page.Dimension): + Physical dimension of the page. + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for the page. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + blocks (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Block]): + A list of visually detected text blocks on + the page. A block has a set of lines (collected + into paragraphs) that have a common line-spacing + and orientation. + paragraphs (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Paragraph]): + A list of visually detected text paragraphs + on the page. A collection of lines that a human + would perceive as a paragraph. + lines (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Line]): + A list of visually detected text lines on the + page. A collection of tokens that a human would + perceive as a line. + tokens (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Token]): + A list of visually detected tokens on the + page. + visual_elements (MutableSequence[google.cloud.documentai_v1.types.Document.Page.VisualElement]): + A list of detected non-text visual elements + e.g. checkbox, signature etc. on the page. + tables (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table]): + A list of visually detected tables on the + page. + form_fields (MutableSequence[google.cloud.documentai_v1.types.Document.Page.FormField]): + A list of visually detected form fields on + the page. + symbols (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Symbol]): + A list of visually detected symbols on the + page. + detected_barcodes (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedBarcode]): + A list of detected barcodes. + image_quality_scores (google.cloud.documentai_v1.types.Document.Page.ImageQualityScores): + Image Quality Scores. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + The history of this page. + """ + + class Dimension(proto.Message): + r"""Dimension for the page. + + Attributes: + width (float): + Page width. + height (float): + Page height. + unit (str): + Dimension unit. + """ + + width: float = proto.Field( + proto.FLOAT, + number=1, + ) + height: float = proto.Field( + proto.FLOAT, + number=2, + ) + unit: str = proto.Field( + proto.STRING, + number=3, + ) + + class Image(proto.Message): + r"""Rendered image contents for this page. + + Attributes: + content (bytes): + Raw byte content of the image. + mime_type (str): + Encoding mime type for the image. + width (int): + Width of the image in pixels. + height (int): + Height of the image in pixels. + """ + + content: bytes = proto.Field( + proto.BYTES, + number=1, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + width: int = proto.Field( + proto.INT32, + number=3, + ) + height: int = proto.Field( + proto.INT32, + number=4, + ) + + class Matrix(proto.Message): + r"""Representation for transformation matrix, intended to be + compatible and used with OpenCV format for image manipulation. + + Attributes: + rows (int): + Number of rows in the matrix. + cols (int): + Number of columns in the matrix. + type_ (int): + This encodes information about what data type the matrix + uses. For example, 0 (CV_8U) is an unsigned 8-bit image. For + the full list of OpenCV primitive data types, please refer + to + https://docs.opencv.org/4.3.0/d1/d1b/group__core__hal__interface.html + data (bytes): + The matrix data. + """ + + rows: int = proto.Field( + proto.INT32, + number=1, + ) + cols: int = proto.Field( + proto.INT32, + number=2, + ) + type_: int = proto.Field( + proto.INT32, + number=3, + ) + data: bytes = proto.Field( + proto.BYTES, + number=4, + ) + + class Layout(proto.Message): + r"""Visual element describing a layout unit on a page. + + Attributes: + text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): + Text anchor indexing into the + [Document.text][google.cloud.documentai.v1.Document.text]. + confidence (float): + Confidence of the current + [Layout][google.cloud.documentai.v1.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]``. + bounding_poly (google.cloud.documentai_v1.types.BoundingPoly): + The bounding polygon for the + [Layout][google.cloud.documentai.v1.Document.Page.Layout]. + orientation (google.cloud.documentai_v1.types.Document.Page.Layout.Orientation): + Detected orientation for the + [Layout][google.cloud.documentai.v1.Document.Page.Layout]. + """ + class Orientation(proto.Enum): + r"""Detected human reading orientation. + + Values: + ORIENTATION_UNSPECIFIED (0): + Unspecified orientation. + PAGE_UP (1): + Orientation is aligned with page up. + PAGE_RIGHT (2): + Orientation is aligned with page right. + Turn the head 90 degrees clockwise from upright + to read. + PAGE_DOWN (3): + Orientation is aligned with page down. + Turn the head 180 degrees from upright to read. + PAGE_LEFT (4): + Orientation is aligned with page left. + Turn the head 90 degrees counterclockwise from + upright to read. + """ + ORIENTATION_UNSPECIFIED = 0 + PAGE_UP = 1 + PAGE_RIGHT = 2 + PAGE_DOWN = 3 + PAGE_LEFT = 4 + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + bounding_poly: geometry.BoundingPoly = proto.Field( + proto.MESSAGE, + number=3, + message=geometry.BoundingPoly, + ) + orientation: 'Document.Page.Layout.Orientation' = proto.Field( + proto.ENUM, + number=4, + enum='Document.Page.Layout.Orientation', + ) + + class Block(proto.Message): + r"""A block has a set of lines (collected into paragraphs) that + have a common line-spacing and orientation. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for [Block][google.cloud.documentai.v1.Document.Page.Block]. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + The history of this annotation. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + class Paragraph(proto.Message): + r"""A collection of lines that a human would perceive as a + paragraph. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for + [Paragraph][google.cloud.documentai.v1.Document.Page.Paragraph]. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + The history of this annotation. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + class Line(proto.Message): + r"""A collection of tokens that a human would perceive as a line. + Does not cross column boundaries, can be horizontal, vertical, + etc. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for [Line][google.cloud.documentai.v1.Document.Page.Line]. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + The history of this annotation. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + class Token(proto.Message): + r"""A detected token. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for [Token][google.cloud.documentai.v1.Document.Page.Token]. + detected_break (google.cloud.documentai_v1.types.Document.Page.Token.DetectedBreak): + Detected break at the end of a + [Token][google.cloud.documentai.v1.Document.Page.Token]. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + The history of this annotation. + """ + + class DetectedBreak(proto.Message): + r"""Detected break at the end of a + [Token][google.cloud.documentai.v1.Document.Page.Token]. + + Attributes: + type_ (google.cloud.documentai_v1.types.Document.Page.Token.DetectedBreak.Type): + Detected break type. + """ + class Type(proto.Enum): + r"""Enum to denote the type of break found. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified break type. + SPACE (1): + A single whitespace. + WIDE_SPACE (2): + A wider whitespace. + HYPHEN (3): + A hyphen that indicates that a token has been + split across lines. + """ + TYPE_UNSPECIFIED = 0 + SPACE = 1 + WIDE_SPACE = 2 + HYPHEN = 3 + + type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( + proto.ENUM, + number=1, + enum='Document.Page.Token.DetectedBreak.Type', + ) + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Token.DetectedBreak', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=4, + message='Document.Provenance', + ) + + class Symbol(proto.Message): + r"""A detected symbol. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for + [Symbol][google.cloud.documentai.v1.Document.Page.Symbol]. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + + class VisualElement(proto.Message): + r"""Detected non-text visual elements e.g. checkbox, signature + etc. on the page. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for + [VisualElement][google.cloud.documentai.v1.Document.Page.VisualElement]. + type_ (str): + Type of the + [VisualElement][google.cloud.documentai.v1.Document.Page.VisualElement]. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + + class Table(proto.Message): + r"""A table representation similar to HTML table structure. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for [Table][google.cloud.documentai.v1.Document.Page.Table]. + header_rows (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): + Header rows of the table. + body_rows (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): + Body rows of the table. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + The history of this table. + """ + + class TableRow(proto.Message): + r"""A row of table cells. + + Attributes: + cells (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableCell]): + Cells that make up this row. + """ + + cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.Page.Table.TableCell', + ) + + class TableCell(proto.Message): + r"""A cell representation inside the table. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for + [TableCell][google.cloud.documentai.v1.Document.Page.Table.TableCell]. + row_span (int): + How many rows this cell spans. + col_span (int): + How many columns this cell spans. + detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + row_span: int = proto.Field( + proto.INT32, + number=2, + ) + col_span: int = proto.Field( + proto.INT32, + number=3, + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.Table.TableRow', + ) + body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.Table.TableRow', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + 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. + + Attributes: + field_name (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for the + [FormField][google.cloud.documentai.v1.Document.Page.FormField] + name. e.g. ``Address``, ``Email``, ``Grand total``, + ``Phone number``, etc. + field_value (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for the + [FormField][google.cloud.documentai.v1.Document.Page.FormField] + value. + name_detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages for name + together with confidence. + value_detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages for value + together with confidence. + value_type (str): + If the value is non-textual, this field represents the type. + Current valid values are: + + - blank (this indicates the ``field_value`` is normal text) + - ``unfilled_checkbox`` + - ``filled_checkbox`` + corrected_key_text (str): + Created for Labeling UI to export key text. If corrections + were made to the text identified by the + ``field_name.text_anchor``, this field will contain the + correction. + corrected_value_text (str): + Created for Labeling UI to export value text. If corrections + were made to the text identified by the + ``field_value.text_anchor``, this field will contain the + correction. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + The history of this annotation. + """ + + field_name: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + field_value: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Layout', + ) + name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + value_type: str = proto.Field( + proto.STRING, + number=5, + ) + corrected_key_text: str = proto.Field( + proto.STRING, + number=6, + ) + corrected_value_text: str = proto.Field( + proto.STRING, + number=7, + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=8, + message='Document.Provenance', + ) + + class DetectedBarcode(proto.Message): + r"""A detected barcode. + + Attributes: + layout (google.cloud.documentai_v1.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1.Document.Page.Layout] + for + [DetectedBarcode][google.cloud.documentai.v1.Document.Page.DetectedBarcode]. + barcode (google.cloud.documentai_v1.types.Barcode): + Detailed barcode information of the + [DetectedBarcode][google.cloud.documentai.v1.Document.Page.DetectedBarcode]. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + barcode: gcd_barcode.Barcode = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_barcode.Barcode, + ) + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + 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]``. + """ + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + 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_v1.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, + ) + image: 'Document.Page.Image' = proto.Field( + proto.MESSAGE, + number=13, + message='Document.Page.Image', + ) + transforms: MutableSequence['Document.Page.Matrix'] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='Document.Page.Matrix', + ) + dimension: 'Document.Page.Dimension' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Dimension', + ) + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Document.Page.Block', + ) + paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Document.Page.Paragraph', + ) + lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Document.Page.Line', + ) + tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Document.Page.Token', + ) + visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Document.Page.VisualElement', + ) + tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Page.Table', + ) + form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='Document.Page.FormField', + ) + symbols: MutableSequence['Document.Page.Symbol'] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='Document.Page.Symbol', + ) + detected_barcodes: MutableSequence['Document.Page.DetectedBarcode'] = proto.RepeatedField( + 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, + message='Document.Provenance', + ) + + class Entity(proto.Message): + r"""An entity that could be a phrase in the text or a property + that belongs to the document. It is a known entity type, such as + a person, an organization, or location. + + Attributes: + text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): + Optional. Provenance of the entity. Text anchor indexing + into the + [Document.text][google.cloud.documentai.v1.Document.text]. + type_ (str): + Required. Entity type from a schema e.g. ``Address``. + mention_text (str): + 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]``. + page_anchor (google.cloud.documentai_v1.types.Document.PageAnchor): + Optional. Represents the provenance of this + entity wrt. the location on the page where it + was found. + id (str): + Optional. Canonical id. This will be a unique + value in the entity list for this document. + normalized_value (google.cloud.documentai_v1.types.Document.Entity.NormalizedValue): + Optional. Normalized entity value. Absent if + the extracted value could not be converted or + the type (e.g. address) is not supported for + certain parsers. This field is also only + populated for certain supported document types. + properties (MutableSequence[google.cloud.documentai_v1.types.Document.Entity]): + Optional. Entities can be nested to form a + hierarchical data structure representing the + content in the document. + provenance (google.cloud.documentai_v1.types.Document.Provenance): + Optional. The history of this annotation. + redacted (bool): + Optional. Whether the entity will be redacted + for de-identification purposes. + """ + + class NormalizedValue(proto.Message): + r"""Parsed and normalized entity value. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + money_value (google.type.money_pb2.Money): + Money value. See also: + https://github.com/googleapis/googleapis/blob/master/google/type/money.proto + + This field is a member of `oneof`_ ``structured_value``. + date_value (google.type.date_pb2.Date): + Date value. Includes year, month, day. See + also: + https://github.com/googleapis/googleapis/blob/master/google/type/date.proto + + This field is a member of `oneof`_ ``structured_value``. + datetime_value (google.type.datetime_pb2.DateTime): + DateTime value. Includes date, time, and + timezone. See also: + https://github.com/googleapis/googleapis/blob/master/google/type/datetime.proto + + This field is a member of `oneof`_ ``structured_value``. + address_value (google.type.postal_address_pb2.PostalAddress): + Postal address. See also: + https://github.com/googleapis/googleapis/blob/master/google/type/postal_address.proto + + This field is a member of `oneof`_ ``structured_value``. + boolean_value (bool): + Boolean value. Can be used for entities with + binary values, or for checkboxes. + + This field is a member of `oneof`_ ``structured_value``. + integer_value (int): + Integer value. + + This field is a member of `oneof`_ ``structured_value``. + float_value (float): + Float value. + + This field is a member of `oneof`_ ``structured_value``. + text (str): + Optional. An optional field to store a normalized string. + For some entity types, one of respective + ``structured_value`` fields may also be populated. Also not + all the types of ``structured_value`` will be normalized. + For example, some processors may not generate ``float`` or + ``integer`` normalized text by default. + + Below are sample formats mapped to structured values. + + - Money/Currency type (``money_value``) is in the ISO 4217 + text format. + - Date type (``date_value``) is in the ISO 8601 text + format. + - Datetime type (``datetime_value``) is in the ISO 8601 + text format. + """ + + money_value: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + oneof='structured_value', + message=money_pb2.Money, + ) + date_value: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + oneof='structured_value', + message=date_pb2.Date, + ) + datetime_value: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=4, + oneof='structured_value', + message=datetime_pb2.DateTime, + ) + address_value: postal_address_pb2.PostalAddress = proto.Field( + proto.MESSAGE, + number=5, + oneof='structured_value', + message=postal_address_pb2.PostalAddress, + ) + boolean_value: bool = proto.Field( + proto.BOOL, + number=6, + oneof='structured_value', + ) + integer_value: int = proto.Field( + proto.INT32, + number=7, + oneof='structured_value', + ) + float_value: float = proto.Field( + proto.FLOAT, + number=8, + oneof='structured_value', + ) + text: str = proto.Field( + proto.STRING, + number=1, + ) + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + mention_text: str = proto.Field( + proto.STRING, + number=3, + ) + mention_id: str = proto.Field( + proto.STRING, + number=4, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=5, + ) + page_anchor: 'Document.PageAnchor' = proto.Field( + proto.MESSAGE, + number=6, + message='Document.PageAnchor', + ) + id: str = proto.Field( + proto.STRING, + number=7, + ) + normalized_value: 'Document.Entity.NormalizedValue' = proto.Field( + proto.MESSAGE, + number=9, + message='Document.Entity.NormalizedValue', + ) + properties: MutableSequence['Document.Entity'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Entity', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=11, + message='Document.Provenance', + ) + redacted: bool = proto.Field( + proto.BOOL, + number=12, + ) + + class EntityRelation(proto.Message): + r"""Relationship between + [Entities][google.cloud.documentai.v1.Document.Entity]. + + Attributes: + subject_id (str): + Subject entity id. + object_id (str): + Object entity id. + relation (str): + Relationship description. + """ + + subject_id: str = proto.Field( + proto.STRING, + number=1, + ) + object_id: str = proto.Field( + proto.STRING, + number=2, + ) + relation: str = proto.Field( + proto.STRING, + number=3, + ) + + class TextAnchor(proto.Message): + r"""Text reference indexing into the + [Document.text][google.cloud.documentai.v1.Document.text]. + + Attributes: + text_segments (MutableSequence[google.cloud.documentai_v1.types.Document.TextAnchor.TextSegment]): + The text segments from the + [Document.text][google.cloud.documentai.v1.Document.text]. + content (str): + Contains the content of the text span so that users do not + have to look it up in the text_segments. It is always + populated for formFields. + """ + + class TextSegment(proto.Message): + r"""A text segment in the + [Document.text][google.cloud.documentai.v1.Document.text]. The + indices may be out of bounds which indicate that the text extends + into another document shard for large sharded documents. See + [ShardInfo.text_offset][google.cloud.documentai.v1.Document.ShardInfo.text_offset] + + Attributes: + start_index (int): + [TextSegment][google.cloud.documentai.v1.Document.TextAnchor.TextSegment] + start UTF-8 char index in the + [Document.text][google.cloud.documentai.v1.Document.text]. + end_index (int): + [TextSegment][google.cloud.documentai.v1.Document.TextAnchor.TextSegment] + half open end UTF-8 char index in the + [Document.text][google.cloud.documentai.v1.Document.text]. + """ + + start_index: int = proto.Field( + proto.INT64, + number=1, + ) + end_index: int = proto.Field( + proto.INT64, + number=2, + ) + + text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.TextAnchor.TextSegment', + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + class PageAnchor(proto.Message): + r"""Referencing the visual context of the entity in the + [Document.pages][google.cloud.documentai.v1.Document.pages]. Page + anchors can be cross-page, consist of multiple bounding polygons and + optionally reference specific layout element types. + + Attributes: + page_refs (MutableSequence[google.cloud.documentai_v1.types.Document.PageAnchor.PageRef]): + One or more references to visual page + elements + """ + + class PageRef(proto.Message): + r"""Represents a weak reference to a page element within a + document. + + Attributes: + page (int): + Required. Index into the + [Document.pages][google.cloud.documentai.v1.Document.pages] + element, for example using + ``[Document.pages][page_refs.page]`` to locate the related + page element. This field is skipped when its value is the + default ``0``. See + https://developers.google.com/protocol-buffers/docs/proto3#json. + layout_type (google.cloud.documentai_v1.types.Document.PageAnchor.PageRef.LayoutType): + Optional. The type of the layout element that + is being referenced if any. + layout_id (str): + Optional. Deprecated. Use + [PageRef.bounding_poly][google.cloud.documentai.v1.Document.PageAnchor.PageRef.bounding_poly] + instead. + bounding_poly (google.cloud.documentai_v1.types.BoundingPoly): + Optional. Identifies the bounding polygon of + a layout element on the page. + confidence (float): + Optional. Confidence of detected page element, if + applicable. Range ``[0, 1]``. + """ + class LayoutType(proto.Enum): + r"""The type of layout that is being referenced. + + Values: + LAYOUT_TYPE_UNSPECIFIED (0): + Layout Unspecified. + BLOCK (1): + References a + [Page.blocks][google.cloud.documentai.v1.Document.Page.blocks] + element. + PARAGRAPH (2): + References a + [Page.paragraphs][google.cloud.documentai.v1.Document.Page.paragraphs] + element. + LINE (3): + References a + [Page.lines][google.cloud.documentai.v1.Document.Page.lines] + element. + TOKEN (4): + References a + [Page.tokens][google.cloud.documentai.v1.Document.Page.tokens] + element. + VISUAL_ELEMENT (5): + References a + [Page.visual_elements][google.cloud.documentai.v1.Document.Page.visual_elements] + element. + TABLE (6): + Refrrences a + [Page.tables][google.cloud.documentai.v1.Document.Page.tables] + element. + FORM_FIELD (7): + References a + [Page.form_fields][google.cloud.documentai.v1.Document.Page.form_fields] + element. + """ + LAYOUT_TYPE_UNSPECIFIED = 0 + BLOCK = 1 + PARAGRAPH = 2 + LINE = 3 + TOKEN = 4 + VISUAL_ELEMENT = 5 + TABLE = 6 + FORM_FIELD = 7 + + page: int = proto.Field( + proto.INT64, + number=1, + ) + layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( + proto.ENUM, + number=2, + enum='Document.PageAnchor.PageRef.LayoutType', + ) + layout_id: str = proto.Field( + proto.STRING, + number=3, + ) + bounding_poly: geometry.BoundingPoly = proto.Field( + proto.MESSAGE, + number=4, + message=geometry.BoundingPoly, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=5, + ) + + page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.PageAnchor.PageRef', + ) + + class Provenance(proto.Message): + r"""Structure to identify provenance relationships between + annotations in different revisions. + + Attributes: + revision (int): + The index of the revision that produced this + element. + id (int): + The Id of this operation. Needs to be unique + within the scope of the revision. + parents (MutableSequence[google.cloud.documentai_v1.types.Document.Provenance.Parent]): + References to the original elements that are + replaced. + type_ (google.cloud.documentai_v1.types.Document.Provenance.OperationType): + The type of provenance operation. + """ + class OperationType(proto.Enum): + r"""If a processor or agent does an explicit operation on + existing elements. + + Values: + OPERATION_TYPE_UNSPECIFIED (0): + Operation type unspecified. If no operation is specified a + provenance entry is simply used to match against a + ``parent``. + ADD (1): + Add an element. + REMOVE (2): + Remove an element identified by ``parent``. + UPDATE (7): + Updates any fields within the given + provenance scope of the message. It 'overwrites' + the fields rather than replacing them. This is + especially relevant when we just want to update + a field value of an entity without also + affecting all the child properties. + REPLACE (3): + Currently unused. Replace an element identified by + ``parent``. + EVAL_REQUESTED (4): + Deprecated. Request human review for the element identified + by ``parent``. + EVAL_APPROVED (5): + Deprecated. Element is reviewed and approved + at human review, confidence will be set to 1.0. + EVAL_SKIPPED (6): + Deprecated. Element is skipped in the + validation process. + """ + OPERATION_TYPE_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + UPDATE = 7 + REPLACE = 3 + EVAL_REQUESTED = 4 + EVAL_APPROVED = 5 + EVAL_SKIPPED = 6 + + class Parent(proto.Message): + r"""The parent element the current element is based on. Used for + referencing/aligning, removal and replacement operations. + + Attributes: + revision (int): + The index of the index into current revision's parent_ids + list. + index (int): + The index of the parent item in the + corresponding item list (eg. list of entities, + properties within entities, etc.) in the parent + revision. + id (int): + The id of the parent provenance. + """ + + revision: int = proto.Field( + proto.INT32, + number=1, + ) + index: int = proto.Field( + proto.INT32, + number=3, + ) + id: int = proto.Field( + proto.INT32, + number=2, + ) + + revision: int = proto.Field( + proto.INT32, + number=1, + ) + id: int = proto.Field( + proto.INT32, + number=2, + ) + parents: MutableSequence['Document.Provenance.Parent'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance.Parent', + ) + type_: 'Document.Provenance.OperationType' = proto.Field( + proto.ENUM, + number=4, + enum='Document.Provenance.OperationType', + ) + + class Revision(proto.Message): + r"""Contains past or forward revisions of this document. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + agent (str): + If the change was made by a person specify + the name or id of that person. + + This field is a member of `oneof`_ ``source``. + processor (str): + If the annotation was made by processor + identify the processor by its resource name. + + This field is a member of `oneof`_ ``source``. + id (str): + Id of the revision, internally generated by + doc proto storage. Unique within the context of + the document. + parent (MutableSequence[int]): + The revisions that this revision is based on. This can + include one or more parent (when documents are merged.) This + field represents the index into the ``revisions`` field. + parent_ids (MutableSequence[str]): + The revisions that this revision is based on. Must include + all the ids that have anything to do with this revision - + eg. there are ``provenance.parent.revision`` fields that + index into this field. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the revision was created, + internally generated by doc proto storage at the + time of create. + human_review (google.cloud.documentai_v1.types.Document.Revision.HumanReview): + Human Review information of this revision. + """ + + class HumanReview(proto.Message): + r"""Human Review information of the document. + + Attributes: + state (str): + Human review state. e.g. ``requested``, ``succeeded``, + ``rejected``. + state_message (str): + A message providing more details about the current state of + processing. For example, the rejection reason when the state + is ``rejected``. + """ + + state: str = proto.Field( + proto.STRING, + number=1, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + + agent: str = proto.Field( + proto.STRING, + number=4, + oneof='source', + ) + processor: str = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + id: str = proto.Field( + proto.STRING, + number=1, + ) + parent: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + parent_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + human_review: 'Document.Revision.HumanReview' = proto.Field( + proto.MESSAGE, + number=6, + message='Document.Revision.HumanReview', + ) + + class TextChange(proto.Message): + r"""This message is used for text changes aka. OCR corrections. + + Attributes: + text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): + Provenance of the correction. Text anchor indexing into the + [Document.text][google.cloud.documentai.v1.Document.text]. + There can only be a single ``TextAnchor.text_segments`` + element. If the start and end index of the text segment are + the same, the text change is inserted before that index. + changed_text (str): + The text that replaces the text identified in the + ``text_anchor``. + provenance (MutableSequence[google.cloud.documentai_v1.types.Document.Provenance]): + The history of this annotation. + """ + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + changed_text: str = proto.Field( + proto.STRING, + number=2, + ) + provenance: MutableSequence['Document.Provenance'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + uri: str = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + content: bytes = proto.Field( + proto.BYTES, + number=2, + oneof='source', + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + text: str = proto.Field( + proto.STRING, + number=4, + ) + text_styles: MutableSequence[Style] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Style, + ) + pages: MutableSequence[Page] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Page, + ) + entities: MutableSequence[Entity] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Entity, + ) + entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=EntityRelation, + ) + text_changes: MutableSequence[TextChange] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=TextChange, + ) + shard_info: ShardInfo = proto.Field( + proto.MESSAGE, + number=9, + message=ShardInfo, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=10, + message=status_pb2.Status, + ) + revisions: MutableSequence[Revision] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=Revision, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py new file mode 100644 index 00000000..ed4912ab --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py @@ -0,0 +1,221 @@ +# -*- 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 + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'RawDocument', + 'GcsDocument', + 'GcsDocuments', + 'GcsPrefix', + 'BatchDocumentsInputConfig', + 'DocumentOutputConfig', + }, +) + + +class RawDocument(proto.Message): + r"""Payload message of raw document content (bytes). + + Attributes: + content (bytes): + Inline document content. + mime_type (str): + An IANA MIME type (RFC6838) indicating the nature and format + of the + [content][google.cloud.documentai.v1.RawDocument.content]. + """ + + content: bytes = proto.Field( + proto.BYTES, + number=1, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GcsDocument(proto.Message): + r"""Specifies a document stored on Cloud Storage. + + Attributes: + gcs_uri (str): + The Cloud Storage object uri. + mime_type (str): + An IANA MIME type (RFC6838) of the content. + """ + + gcs_uri: str = proto.Field( + proto.STRING, + number=1, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GcsDocuments(proto.Message): + r"""Specifies a set of documents on Cloud Storage. + + Attributes: + documents (MutableSequence[google.cloud.documentai_v1.types.GcsDocument]): + The list of documents. + """ + + documents: MutableSequence['GcsDocument'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GcsDocument', + ) + + +class GcsPrefix(proto.Message): + r"""Specifies all documents on Cloud Storage with a common + prefix. + + Attributes: + gcs_uri_prefix (str): + The URI prefix. + """ + + gcs_uri_prefix: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchDocumentsInputConfig(proto.Message): + r"""The common config to specify a set of documents used as + input. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (google.cloud.documentai_v1.types.GcsPrefix): + The set of documents that match the specified Cloud Storage + ``gcs_prefix``. + + This field is a member of `oneof`_ ``source``. + gcs_documents (google.cloud.documentai_v1.types.GcsDocuments): + The set of documents individually specified + on Cloud Storage. + + This field is a member of `oneof`_ ``source``. + """ + + gcs_prefix: 'GcsPrefix' = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsPrefix', + ) + gcs_documents: 'GcsDocuments' = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsDocuments', + ) + + +class DocumentOutputConfig(proto.Message): + r"""Config that controls the output of documents. All documents + will be written as a JSON file. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_output_config (google.cloud.documentai_v1.types.DocumentOutputConfig.GcsOutputConfig): + Output config to write the results to Cloud + Storage. + + This field is a member of `oneof`_ ``destination``. + """ + + class GcsOutputConfig(proto.Message): + r"""The configuration used when outputting documents. + + Attributes: + gcs_uri (str): + The Cloud Storage uri (a directory) of the + output. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Specifies which fields to include in the output documents. + Only supports top level document and pages field so it must + be in the form of ``{document_field_name}`` or + ``pages.{page_field_name}``. + sharding_config (google.cloud.documentai_v1.types.DocumentOutputConfig.GcsOutputConfig.ShardingConfig): + Specifies the sharding config for the output + document. + """ + + class ShardingConfig(proto.Message): + r"""The sharding config for the output document. + + Attributes: + pages_per_shard (int): + The number of pages per shard. + pages_overlap (int): + The number of overlapping pages between + consecutive shards. + """ + + pages_per_shard: int = proto.Field( + proto.INT32, + number=1, + ) + pages_overlap: int = proto.Field( + proto.INT32, + number=2, + ) + + gcs_uri: str = proto.Field( + proto.STRING, + number=1, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + sharding_config: 'DocumentOutputConfig.GcsOutputConfig.ShardingConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='DocumentOutputConfig.GcsOutputConfig.ShardingConfig', + ) + + gcs_output_config: GcsOutputConfig = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message=GcsOutputConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py new file mode 100644 index 00000000..2ffbac1e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py @@ -0,0 +1,1361 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.documentai_v1.types import document as gcd_document +from google.cloud.documentai_v1.types import document_io +from google.cloud.documentai_v1.types import document_schema as gcd_document_schema +from google.cloud.documentai_v1.types import evaluation as gcd_evaluation +from google.cloud.documentai_v1.types import operation_metadata +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'ProcessRequest', + 'HumanReviewStatus', + 'ProcessResponse', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'BatchProcessMetadata', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'GetProcessorTypeRequest', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'DeleteProcessorVersionRequest', + 'DeleteProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'CreateProcessorRequest', + 'DeleteProcessorRequest', + 'DeleteProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EnableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'DisableProcessorMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'SetDefaultProcessorVersionMetadata', + 'TrainProcessorVersionRequest', + 'TrainProcessorVersionResponse', + 'TrainProcessorVersionMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'ReviewDocumentOperationMetadata', + 'EvaluateProcessorVersionRequest', + 'EvaluateProcessorVersionMetadata', + 'EvaluateProcessorVersionResponse', + 'GetEvaluationRequest', + 'ListEvaluationsRequest', + 'ListEvaluationsResponse', + }, +) + + +class ProcessRequest(proto.Message): + r"""Request message for the process document method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_document (google.cloud.documentai_v1.types.Document): + An inline document proto. + + This field is a member of `oneof`_ ``source``. + raw_document (google.cloud.documentai_v1.types.RawDocument): + A raw document content (bytes). + + This field is a member of `oneof`_ ``source``. + name (str): + Required. The resource name of the + [Processor][google.cloud.documentai.v1.Processor] or + [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] + to use for processing. If a + [Processor][google.cloud.documentai.v1.Processor] is + specified, the server will use its [default + version][google.cloud.documentai.v1.Processor.default_processor_version]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + skip_human_review (bool): + 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. 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( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + raw_document: document_io.RawDocument = proto.Field( + proto.MESSAGE, + number=5, + oneof='source', + message=document_io.RawDocument, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + skip_human_review: bool = proto.Field( + proto.BOOL, + number=3, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=6, + message=field_mask_pb2.FieldMask, + ) + + +class HumanReviewStatus(proto.Message): + r"""The status of human review on a processed document. + + Attributes: + state (google.cloud.documentai_v1.types.HumanReviewStatus.State): + The state of human review on the processing + request. + state_message (str): + A message providing more details about the + human review state. + human_review_operation (str): + The name of the operation triggered by the processed + document. This field is populated only when the [state] is + [HUMAN_REVIEW_IN_PROGRESS]. It has the same response type + and metadata as the long running operation returned by + [ReviewDocument] method. + """ + class State(proto.Enum): + r"""The final state of human review on a processed document. + + Values: + STATE_UNSPECIFIED (0): + Human review state is unspecified. Most + likely due to an internal error. + SKIPPED (1): + Human review is skipped for the document. + This can happen because human review is not + enabled on the processor or the processing + request has been set to skip this document. + VALIDATION_PASSED (2): + Human review validation is triggered and + passed, so no review is needed. + IN_PROGRESS (3): + Human review validation is triggered and the + document is under review. + ERROR (4): + Some error happened during triggering human review, see the + [state_message] for details. + """ + STATE_UNSPECIFIED = 0 + SKIPPED = 1 + VALIDATION_PASSED = 2 + IN_PROGRESS = 3 + ERROR = 4 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + human_review_operation: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ProcessResponse(proto.Message): + r"""Response message for the process document method. + + Attributes: + document (google.cloud.documentai_v1.types.Document): + The document payload, will populate fields + based on the processor's behavior. + human_review_status (google.cloud.documentai_v1.types.HumanReviewStatus): + The status of human review on the processed + document. + """ + + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + human_review_status: 'HumanReviewStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='HumanReviewStatus', + ) + + +class BatchProcessRequest(proto.Message): + r"""Request message for batch process document method. + + Attributes: + name (str): + Required. The resource name of + [Processor][google.cloud.documentai.v1.Processor] or + [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + input_documents (google.cloud.documentai_v1.types.BatchDocumentsInputConfig): + The input documents for batch process. + document_output_config (google.cloud.documentai_v1.types.DocumentOutputConfig): + The overall output config for batch process. + skip_human_review (bool): + Whether Human Review feature should be + skipped for this request. Default to false. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + input_documents: document_io.BatchDocumentsInputConfig = proto.Field( + proto.MESSAGE, + number=5, + message=document_io.BatchDocumentsInputConfig, + ) + document_output_config: document_io.DocumentOutputConfig = proto.Field( + proto.MESSAGE, + number=6, + message=document_io.DocumentOutputConfig, + ) + skip_human_review: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class BatchProcessResponse(proto.Message): + r"""Response message for batch process document method. + """ + + +class BatchProcessMetadata(proto.Message): + r"""The long running operation metadata for batch process method. + + Attributes: + state (google.cloud.documentai_v1.types.BatchProcessMetadata.State): + The state of the current batch processing. + state_message (str): + A message providing more details about the + current state of processing. For example, the + error message if the operation is failed. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update time of the operation. + individual_process_statuses (MutableSequence[google.cloud.documentai_v1.types.BatchProcessMetadata.IndividualProcessStatus]): + The list of response details of each + document. + """ + class State(proto.Enum): + r"""Possible states of the batch processing operation. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + WAITING (1): + Request operation is waiting for scheduling. + RUNNING (2): + Request is being processed. + SUCCEEDED (3): + The batch processing completed successfully. + CANCELLING (4): + The batch processing was being cancelled. + CANCELLED (5): + The batch processing was cancelled. + FAILED (6): + The batch processing has failed. + """ + STATE_UNSPECIFIED = 0 + WAITING = 1 + RUNNING = 2 + SUCCEEDED = 3 + CANCELLING = 4 + CANCELLED = 5 + FAILED = 6 + + class IndividualProcessStatus(proto.Message): + r"""The status of a each individual document in the batch + process. + + Attributes: + input_gcs_source (str): + The source of the document, same as the [input_gcs_source] + field in the request when the batch process started. The + batch process is started by take snapshot of that document, + since a user can move or change that document during the + process. + status (google.rpc.status_pb2.Status): + The status processing the document. + output_gcs_destination (str): + The output_gcs_destination (in the request as + ``output_gcs_destination``) of the processed document if it + was successful, otherwise empty. + human_review_status (google.cloud.documentai_v1.types.HumanReviewStatus): + The status of human review on the processed + document. + """ + + input_gcs_source: str = proto.Field( + proto.STRING, + number=1, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + output_gcs_destination: str = proto.Field( + proto.STRING, + number=3, + ) + human_review_status: 'HumanReviewStatus' = proto.Field( + proto.MESSAGE, + number=5, + message='HumanReviewStatus', + ) + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + individual_process_statuses: MutableSequence[IndividualProcessStatus] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=IndividualProcessStatus, + ) + + +class FetchProcessorTypesRequest(proto.Message): + r"""Request message for fetch processor types. + + Attributes: + parent (str): + Required. The project of processor type to list. The + available processor types may depend on the allow-listing on + projects. Format: + ``projects/{project}/locations/{location}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchProcessorTypesResponse(proto.Message): + r"""Response message for fetch processor types. + + Attributes: + processor_types (MutableSequence[google.cloud.documentai_v1.types.ProcessorType]): + The list of processor types. + """ + + processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=processor_type.ProcessorType, + ) + + +class ListProcessorTypesRequest(proto.Message): + r"""Request message for list processor types. + + Attributes: + parent (str): + Required. The location of processor type to list. The + available processor types may depend on the allow-listing on + projects. Format: + ``projects/{project}/locations/{location}`` + page_size (int): + The maximum number of processor types to + return. If unspecified, at most 100 processor + types will be returned. The maximum value is + 500; values above 500 will be coerced to 500. + page_token (str): + Used to retrieve the next page of results, + empty if at the end of the list. + """ + + 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 ListProcessorTypesResponse(proto.Message): + r"""Response message for list processor types. + + Attributes: + processor_types (MutableSequence[google.cloud.documentai_v1.types.ProcessorType]): + The processor types. + next_page_token (str): + Points to the next page, otherwise empty. + """ + + @property + def raw_page(self): + return self + + processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=processor_type.ProcessorType, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListProcessorsRequest(proto.Message): + r"""Request message for list all processors belongs to a project. + + Attributes: + parent (str): + Required. The parent (project and location) which owns this + collection of Processors. Format: + ``projects/{project}/locations/{location}`` + page_size (int): + The maximum number of processors to return. + If unspecified, at most 50 processors will be + returned. The maximum value is 100; values above + 100 will be coerced to 100. + page_token (str): + We will return the processors sorted by + creation time. The page token will point to the + next processor. + """ + + 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 ListProcessorsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processors (MutableSequence[google.cloud.documentai_v1.types.Processor]): + The list of processors. + next_page_token (str): + Points to the next processor, otherwise + empty. + """ + + @property + def raw_page(self): + return self + + processors: MutableSequence[gcd_processor.Processor] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.Processor, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetProcessorTypeRequest(proto.Message): + r"""Request message for get processor. + + Attributes: + name (str): + Required. The processor type resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetProcessorRequest(proto.Message): + r"""Request message for get processor. + + Attributes: + name (str): + Required. The processor resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetProcessorVersionRequest(proto.Message): + r"""Request message for get processor version. + + Attributes: + name (str): + Required. The processor resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProcessorVersionsRequest(proto.Message): + r"""Request message for list all processor versions belongs to a + processor. + + Attributes: + parent (str): + Required. The parent (project, location and processor) to + list all versions. Format: + ``projects/{project}/locations/{location}/processors/{processor}`` + page_size (int): + The maximum number of processor versions to + return. If unspecified, at most 10 processor + versions will be returned. The maximum value is + 20; values above 20 will be coerced to 20. + page_token (str): + We will return the processor versions sorted + by creation time. The page token will point to + the next processor version. + """ + + 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 ListProcessorVersionsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processor_versions (MutableSequence[google.cloud.documentai_v1.types.ProcessorVersion]): + The list of processors. + next_page_token (str): + Points to the next processor, otherwise + empty. + """ + + @property + def raw_page(self): + return self + + processor_versions: MutableSequence[gcd_processor.ProcessorVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.ProcessorVersion, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteProcessorVersionRequest(proto.Message): + r"""Request message for the delete processor version method. + + Attributes: + name (str): + Required. The processor version resource name + to be deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for delete processor + version method. + + Attributes: + common_metadata (google.cloud.documentai_v1.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 DeployProcessorVersionRequest(proto.Message): + r"""Request message for the deploy processor version method. + + Attributes: + name (str): + Required. The processor version resource name + to be deployed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeployProcessorVersionResponse(proto.Message): + r"""Response message for the deploy processor version method. + """ + + +class DeployProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for deploy processor + version method. + + Attributes: + common_metadata (google.cloud.documentai_v1.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 UndeployProcessorVersionRequest(proto.Message): + r"""Request message for the undeploy processor version method. + + Attributes: + name (str): + Required. The processor version resource name + to be undeployed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeployProcessorVersionResponse(proto.Message): + r"""Response message for the undeploy processor version method. + """ + + +class UndeployProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for the undeploy + processor version method. + + Attributes: + common_metadata (google.cloud.documentai_v1.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 CreateProcessorRequest(proto.Message): + r"""Request message for create a processor. Notice this request + is sent to a regionalized backend service, and if the processor + type is not available on that region, the creation will fail. + + Attributes: + parent (str): + Required. The parent (project and location) under which to + create the processor. Format: + ``projects/{project}/locations/{location}`` + processor (google.cloud.documentai_v1.types.Processor): + Required. The processor to be created, requires + [processor_type] and [display_name] to be set. Also, the + processor is under CMEK if CMEK fields are set. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + processor: gcd_processor.Processor = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_processor.Processor, + ) + + +class DeleteProcessorRequest(proto.Message): + r"""Request message for the delete processor method. + + Attributes: + name (str): + Required. The processor resource name to be + deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteProcessorMetadata(proto.Message): + r"""The long running operation metadata for delete processor + method. + + Attributes: + common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + """ + + common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=operation_metadata.CommonOperationMetadata, + ) + + +class EnableProcessorRequest(proto.Message): + r"""Request message for the enable processor method. + + Attributes: + name (str): + Required. The processor resource name to be + enabled. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EnableProcessorResponse(proto.Message): + r"""Response message for the enable processor method. + Intentionally empty proto for adding fields in future. + + """ + + +class EnableProcessorMetadata(proto.Message): + r"""The long running operation metadata for enable processor + method. + + Attributes: + common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + """ + + common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=operation_metadata.CommonOperationMetadata, + ) + + +class DisableProcessorRequest(proto.Message): + r"""Request message for the disable processor method. + + Attributes: + name (str): + Required. The processor resource name to be + disabled. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableProcessorResponse(proto.Message): + r"""Response message for the disable processor method. + Intentionally empty proto for adding fields in future. + + """ + + +class DisableProcessorMetadata(proto.Message): + r"""The long running operation metadata for disable processor + method. + + Attributes: + common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + """ + + common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=operation_metadata.CommonOperationMetadata, + ) + + +class SetDefaultProcessorVersionRequest(proto.Message): + r"""Request message for the set default processor version method. + + Attributes: + processor (str): + Required. The resource name of the + [Processor][google.cloud.documentai.v1.Processor] to change + default version. + default_processor_version (str): + Required. The resource name of child + [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] + to use as default. Format: + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{version}`` + """ + + processor: str = proto.Field( + proto.STRING, + number=1, + ) + default_processor_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SetDefaultProcessorVersionResponse(proto.Message): + r"""Response message for set default processor version method. + """ + + +class SetDefaultProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for set default processor + version method. + + Attributes: + common_metadata (google.cloud.documentai_v1.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 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_v1.types.ProcessorVersion): + Required. The processor version to be + created. + document_schema (google.cloud.documentai_v1.types.DocumentSchema): + Optional. The schema the processor version + will be trained with. + input_data (google.cloud.documentai_v1.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_v1.types.BatchDocumentsInputConfig): + The documents used for training the new + version. + test_documents (google.cloud.documentai_v1.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_v1.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + training_dataset_validation (google.cloud.documentai_v1.types.TrainProcessorVersionMetadata.DatasetValidation): + The training dataset validation information. + test_dataset_validation (google.cloud.documentai_v1.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. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_document (google.cloud.documentai_v1.types.Document): + An inline document proto. + + This field is a member of `oneof`_ ``source``. + human_review_config (str): + Required. The resource name of the + HumanReviewConfig that the document will be + reviewed with. + enable_schema_validation (bool): + Whether the validation should be performed on + the ad-hoc review request. + priority (google.cloud.documentai_v1.types.ReviewDocumentRequest.Priority): + The priority of the human review task. + document_schema (google.cloud.documentai_v1.types.DocumentSchema): + The document schema of the human review task. + """ + class Priority(proto.Enum): + r"""The priority level of the human review task. + + Values: + DEFAULT (0): + The default priority level. + URGENT (1): + The urgent priority level. The labeling + manager should allocate labeler resource to the + urgent task queue to respect this priority + level. + """ + DEFAULT = 0 + URGENT = 1 + + inline_document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + human_review_config: str = proto.Field( + proto.STRING, + number=1, + ) + enable_schema_validation: bool = proto.Field( + proto.BOOL, + number=3, + ) + priority: Priority = proto.Field( + proto.ENUM, + number=5, + enum=Priority, + ) + document_schema: gcd_document_schema.DocumentSchema = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_document_schema.DocumentSchema, + ) + + +class ReviewDocumentResponse(proto.Message): + r"""Response message for review document method. + + Attributes: + gcs_destination (str): + The Cloud Storage uri for the human reviewed + document if the review is succeeded. + state (google.cloud.documentai_v1.types.ReviewDocumentResponse.State): + The state of the review operation. + rejection_reason (str): + The reason why the review is rejected by + reviewer. + """ + class State(proto.Enum): + r"""Possible states of the review operation. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + REJECTED (1): + The review operation is rejected by the + reviewer. + SUCCEEDED (2): + The review operation is succeeded. + """ + STATE_UNSPECIFIED = 0 + REJECTED = 1 + SUCCEEDED = 2 + + gcs_destination: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + rejection_reason: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ReviewDocumentOperationMetadata(proto.Message): + r"""The long running operation metadata for review document + method. + + Attributes: + common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + question_id (str): + The Crowd Compute question ID. + """ + + common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=operation_metadata.CommonOperationMetadata, + ) + question_id: str = proto.Field( + proto.STRING, + number=6, + ) + + +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.v1.ProcessorVersion] + to evaluate. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + evaluation_documents (google.cloud.documentai_v1.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_v1.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.v1.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.v1.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_v1.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/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py new file mode 100644 index 00000000..3506f466 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py @@ -0,0 +1,250 @@ +# -*- 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 + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'DocumentSchema', + }, +) + + +class DocumentSchema(proto.Message): + r"""The schema defines the output of the processed document by a + processor. + + Attributes: + display_name (str): + Display name to show to users. + description (str): + Description of the schema. + entity_types (MutableSequence[google.cloud.documentai_v1.types.DocumentSchema.EntityType]): + Entity types of the schema. + metadata (google.cloud.documentai_v1.types.DocumentSchema.Metadata): + Metadata of the schema. + """ + + class EntityType(proto.Message): + r"""EntityType is the wrapper of a label of the corresponding + model with detailed attributes and limitations for entity-based + processors. Multiple types can also compose a dependency tree to + represent nested types. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enum_values (google.cloud.documentai_v1.types.DocumentSchema.EntityType.EnumValues): + If specified, lists all the possible values for this entity. + This should not be more than a handful of values. If the + number of values is >10 or could change frequently use the + ``EntityType.value_ontology`` field and specify a list of + all possible values in a value ontology file. + + This field is a member of `oneof`_ ``value_source``. + display_name (str): + User defined name for the type. + name (str): + Name of the type. It must be unique within the schema file + and cannot be a 'Common Type'. Besides that we use the + following naming conventions: + + - *use ``snake_casing``* + - name matching is case-sensitive + - 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 + compatibility. + base_types (MutableSequence[str]): + The entity type that this type is derived + from. For now, one and only one should be set. + properties (MutableSequence[google.cloud.documentai_v1.types.DocumentSchema.EntityType.Property]): + Description the nested structure, or + composition of an entity. + """ + + class EnumValues(proto.Message): + r"""Defines the a list of enum values. + + Attributes: + values (MutableSequence[str]): + The individual values that this enum values + type can include. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Property(proto.Message): + r"""Defines properties that can be part of the entity type. + + Attributes: + name (str): + The name of the property. Follows the same + guidelines as the EntityType name. + value_type (str): + A reference to the value type of the property. This type is + subject to the same conventions as the ``Entity.base_types`` + field. + occurrence_type (google.cloud.documentai_v1.types.DocumentSchema.EntityType.Property.OccurrenceType): + Occurrence type limits the number of + instances an entity type appears in the + document. + """ + class OccurrenceType(proto.Enum): + r"""Types of occurrences of the entity type in the document. This + represents the number of instances of instances of an entity, not + number of mentions of an entity. For example, a bank statement may + only have one ``account_number``, but this account number may be + mentioned in several places on the document. In this case the + 'account_number' would be considered a ``REQUIRED_ONCE`` entity + type. If, on the other hand, we expect a bank statement to contain + the status of multiple different accounts for the customers, the + occurrence type will be set to ``REQUIRED_MULTIPLE``. + + Values: + OCCURRENCE_TYPE_UNSPECIFIED (0): + Unspecified occurrence type. + OPTIONAL_ONCE (1): + There will be zero or one instance of this + entity type. The same entity instance may be + mentioned multiple times. + OPTIONAL_MULTIPLE (2): + The entity type will appear zero or multiple + times. + REQUIRED_ONCE (3): + The entity type will only appear exactly + once. The same entity instance may be mentioned + multiple times. + REQUIRED_MULTIPLE (4): + The entity type will appear once or more + times. + """ + OCCURRENCE_TYPE_UNSPECIFIED = 0 + OPTIONAL_ONCE = 1 + OPTIONAL_MULTIPLE = 2 + REQUIRED_ONCE = 3 + REQUIRED_MULTIPLE = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value_type: str = proto.Field( + proto.STRING, + number=2, + ) + occurrence_type: 'DocumentSchema.EntityType.Property.OccurrenceType' = proto.Field( + proto.ENUM, + number=3, + enum='DocumentSchema.EntityType.Property.OccurrenceType', + ) + + enum_values: 'DocumentSchema.EntityType.EnumValues' = proto.Field( + proto.MESSAGE, + number=14, + oneof='value_source', + message='DocumentSchema.EntityType.EnumValues', + ) + display_name: str = proto.Field( + proto.STRING, + number=13, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + base_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + properties: MutableSequence['DocumentSchema.EntityType.Property'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='DocumentSchema.EntityType.Property', + ) + + class Metadata(proto.Message): + r"""Metadata for global schema behavior. + + Attributes: + document_splitter (bool): + If true, a ``document`` entity type can be applied to + subdocument ( splitting). Otherwise, it can only be applied + to the entire document (classification). + document_allow_multiple_labels (bool): + If true, on a given page, there can be multiple ``document`` + annotations covering it. + prefixed_naming_on_properties (bool): + If set, all the nested entities must be + prefixed with the parents. + skip_naming_validation (bool): + If set, we will skip the naming format validation in the + schema. So the string values in + ``DocumentSchema.EntityType.name`` and + ``DocumentSchema.EntityType.Property.name`` will not be + checked. + """ + + document_splitter: bool = proto.Field( + proto.BOOL, + number=1, + ) + document_allow_multiple_labels: bool = proto.Field( + proto.BOOL, + number=2, + ) + prefixed_naming_on_properties: bool = proto.Field( + proto.BOOL, + number=6, + ) + skip_naming_validation: bool = proto.Field( + proto.BOOL, + number=7, + ) + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + entity_types: MutableSequence[EntityType] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=EntityType, + ) + metadata: Metadata = proto.Field( + proto.MESSAGE, + number=4, + message=Metadata, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/evaluation.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/evaluation.py new file mode 100644 index 00000000..6483282d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/evaluation.py @@ -0,0 +1,342 @@ +# -*- 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 + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'EvaluationReference', + 'Evaluation', + }, +) + + +class EvaluationReference(proto.Message): + r"""Gives a short summary of an evaluation, and links to the + evaluation itself. + + Attributes: + operation (str): + The resource name of the Long Running + Operation for the evaluation. + evaluation (str): + The resource name of the evaluation. + aggregate_metrics (google.cloud.documentai_v1.types.Evaluation.Metrics): + An aggregate of the statistics for the + evaluation with fuzzy matching on. + aggregate_metrics_exact (google.cloud.documentai_v1.types.Evaluation.Metrics): + An aggregate of the statistics for the + evaluation with fuzzy matching off. + """ + + operation: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation: str = proto.Field( + proto.STRING, + number=2, + ) + aggregate_metrics: 'Evaluation.Metrics' = proto.Field( + proto.MESSAGE, + number=4, + message='Evaluation.Metrics', + ) + aggregate_metrics_exact: 'Evaluation.Metrics' = proto.Field( + proto.MESSAGE, + number=5, + message='Evaluation.Metrics', + ) + + +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_v1.types.Evaluation.Counters): + Counters for the documents used in the + evaluation. + all_entities_metrics (google.cloud.documentai_v1.types.Evaluation.MultiConfidenceMetrics): + Metrics for all the entities in aggregate. + entity_metrics (MutableMapping[str, google.cloud.documentai_v1.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_v1.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_v1.types.Evaluation.ConfidenceLevelMetrics]): + Metrics across confidence levels with fuzzy + matching enabled. + confidence_level_metrics_exact (MutableSequence[google.cloud.documentai_v1.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_v1.types.Evaluation.MultiConfidenceMetrics.MetricsType): + The metrics type for the label. + """ + class MetricsType(proto.Enum): + r"""A type that determines how metrics should be interpreted. + + Values: + METRICS_TYPE_UNSPECIFIED (0): + The metrics type is unspecified. By default, + metrics without a particular specification are + for leaf entity types (i.e., top-level entity + types without child types, or child types which + are not parent types themselves). + AGGREGATE (1): + Indicates whether metrics for this particular + label type represent an aggregate of metrics for + other types instead of being based on actual + TP/FP/FN values for the label type. Metrics for + parent (i.e., non-leaf) entity types are an + aggregate of metrics for their children. + """ + 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/owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py new file mode 100644 index 00000000..9f3ebd78 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py @@ -0,0 +1,99 @@ +# -*- 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 + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + }, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate (starts from the top of the + image). + """ + + x: int = proto.Field( + proto.INT32, + number=1, + ) + y: int = proto.Field( + proto.INT32, + number=2, + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate (starts from the top of the + image). + """ + + x: float = proto.Field( + proto.FLOAT, + number=1, + ) + y: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (MutableSequence[google.cloud.documentai_v1.types.Vertex]): + The bounding polygon vertices. + normalized_vertices (MutableSequence[google.cloud.documentai_v1.types.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices: MutableSequence['Vertex'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='NormalizedVertex', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py new file mode 100644 index 00000000..9053ca49 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py @@ -0,0 +1,96 @@ +# -*- 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 + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'CommonOperationMetadata', + }, +) + + +class CommonOperationMetadata(proto.Message): + r"""The common metadata for long running operations. + + Attributes: + state (google.cloud.documentai_v1.types.CommonOperationMetadata.State): + The state of the operation. + state_message (str): + A message providing more details about the + current state of processing. + resource (str): + A related resource to this operation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update time of the operation. + """ + class State(proto.Enum): + r"""State of the longrunning operation. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + RUNNING (1): + Operation is still running. + CANCELLING (2): + Operation is being cancelled. + SUCCEEDED (3): + Operation succeeded. + FAILED (4): + Operation failed. + CANCELLED (5): + Operation is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + CANCELLING = 2 + SUCCEEDED = 3 + FAILED = 4 + CANCELLED = 5 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + resource: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py new file mode 100644 index 00000000..e3912e16 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py @@ -0,0 +1,285 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.documentai_v1.types import document_schema as gcd_document_schema +from google.cloud.documentai_v1.types import evaluation +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'ProcessorVersion', + 'Processor', + }, +) + + +class ProcessorVersion(proto.Message): + r"""A processor version is an implementation of a processor. Each + processor can have multiple versions, pre-trained by Google + internally or up-trained by the customer. At a time, a processor + can only have one default version version. So the processor's + behavior (when processing documents) is defined by a default + version + + Attributes: + name (str): + The resource name of the processor version. Format: + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}`` + display_name (str): + The display name of the processor version. + document_schema (google.cloud.documentai_v1.types.DocumentSchema): + The schema of the processor version. + Describes the output. + state (google.cloud.documentai_v1.types.ProcessorVersion.State): + The state of the processor version. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the processor version was created. + latest_evaluation (google.cloud.documentai_v1.types.EvaluationReference): + The most recently invoked evaluation for the + processor version. + 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. + google_managed (bool): + Denotes that this ProcessorVersion is managed + by google. + deprecation_info (google.cloud.documentai_v1.types.ProcessorVersion.DeprecationInfo): + If set, information about the eventual + deprecation of this version. + """ + class State(proto.Enum): + r"""The possible states of the processor version. + + Values: + STATE_UNSPECIFIED (0): + The processor version is in an unspecified + state. + DEPLOYED (1): + The processor version is deployed and can be + used for processing. + DEPLOYING (2): + The processor version is being deployed. + UNDEPLOYED (3): + The processor version is not deployed and + cannot be used for processing. + UNDEPLOYING (4): + The processor version is being undeployed. + CREATING (5): + The processor version is being created. + DELETING (6): + The processor version is being deleted. + FAILED (7): + The processor version failed and is in an + indeterminate state. + """ + STATE_UNSPECIFIED = 0 + DEPLOYED = 1 + DEPLOYING = 2 + UNDEPLOYED = 3 + UNDEPLOYING = 4 + CREATING = 5 + DELETING = 6 + FAILED = 7 + + class DeprecationInfo(proto.Message): + r"""Information about the upcoming deprecation of this processor + version. + + Attributes: + deprecation_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which this processor version will + be deprecated. + replacement_processor_version (str): + If set, the processor version that will be + used as a replacement. + """ + + deprecation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + replacement_processor_version: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + 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, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + latest_evaluation: evaluation.EvaluationReference = proto.Field( + proto.MESSAGE, + number=8, + message=evaluation.EvaluationReference, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=9, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=10, + ) + google_managed: bool = proto.Field( + proto.BOOL, + number=11, + ) + deprecation_info: DeprecationInfo = proto.Field( + proto.MESSAGE, + number=13, + message=DeprecationInfo, + ) + + +class Processor(proto.Message): + r"""The first-class citizen for Document AI. Each processor + defines how to extract structural information from a document. + + Attributes: + name (str): + Output only. Immutable. The resource name of the processor. + 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 + [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes]. + display_name (str): + The display name of the processor. + state (google.cloud.documentai_v1.types.Processor.State): + Output only. The state of the processor. + default_processor_version (str): + The default processor version. + process_endpoint (str): + Output only. Immutable. The http endpoint + that can be called to invoke processing. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the processor was created. + kms_key_name (str): + The KMS key used for encryption/decryption in + CMEK scenarios. See + https://cloud.google.com/security-key-management. + """ + class State(proto.Enum): + r"""The possible states of the processor. + + Values: + STATE_UNSPECIFIED (0): + The processor is in an unspecified state. + ENABLED (1): + The processor is enabled, i.e., has an + enabled version which can currently serve + processing requests and all the feature + dependencies have been successfully initialized. + DISABLED (2): + The processor is disabled. + ENABLING (3): + The processor is being enabled, will become ``ENABLED`` if + successful. + DISABLING (4): + The processor is being disabled, will become ``DISABLED`` if + successful. + CREATING (5): + The processor is being created, will become either + ``ENABLED`` (for successful creation) or ``FAILED`` (for + failed ones). Once a processor is in this state, it can then + be used for document processing, but the feature + dependencies of the processor might not be fully created + yet. + FAILED (6): + The processor failed during creation or + initialization of feature dependencies. The user + should delete the processor and recreate one as + all the functionalities of the processor are + disabled. + DELETING (7): + The processor is being deleted, will be + removed if successful. + """ + STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + ENABLING = 3 + DISABLING = 4 + CREATING = 5 + FAILED = 6 + DELETING = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + default_processor_version: str = proto.Field( + proto.STRING, + number=9, + ) + process_endpoint: str = proto.Field( + proto.STRING, + number=6, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py new file mode 100644 index 00000000..bb0e0339 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py @@ -0,0 +1,106 @@ +# -*- 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 + +import proto # type: ignore + +from google.api import launch_stage_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1', + manifest={ + 'ProcessorType', + }, +) + + +class ProcessorType(proto.Message): + r"""A processor type is responsible for performing a certain + document understanding task on a certain type of document. + + Attributes: + name (str): + The resource name of the processor type. Format: + ``projects/{project}/processorTypes/{processor_type}`` + type_ (str): + The processor type, e.g., ``OCR_PROCESSOR``, + ``INVOICE_PROCESSOR``, etc. + category (str): + The processor category, used by UI to group + processor types. + available_locations (MutableSequence[google.cloud.documentai_v1.types.ProcessorType.LocationInfo]): + The locations in which this processor is + available. + allow_creation (bool): + Whether the processor type allows creation. + If true, users can create a processor of this + processor type. Otherwise, users need to request + access. + launch_stage (google.api.launch_stage_pb2.LaunchStage): + Launch stage of the processor type + sample_document_uris (MutableSequence[str]): + A set of Cloud Storage URIs of sample + documents for this processor. + """ + + class LocationInfo(proto.Message): + r"""The location information about where the processor is + available. + + Attributes: + location_id (str): + The location id, currently must be one of [us, eu]. + """ + + location_id: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + category: str = proto.Field( + proto.STRING, + number=3, + ) + available_locations: MutableSequence[LocationInfo] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=LocationInfo, + ) + allow_creation: bool = proto.Field( + proto.BOOL, + number=6, + ) + launch_stage: launch_stage_pb2.LaunchStage = proto.Field( + proto.ENUM, + number=8, + enum=launch_stage_pb2.LaunchStage, + ) + sample_document_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 00000000..e59b31ef --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- 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. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/documentai_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py new file mode 100644 index 00000000..5801f218 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_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 BatchProcessDocuments +# 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_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1 + + +async def sample_batch_process_documents(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py new file mode 100644 index 00000000..0d0d911a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_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 BatchProcessDocuments +# 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_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1 + + +def sample_batch_process_documents(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py new file mode 100644 index 00000000..e641612b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_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 CreateProcessor +# 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_v1_generated_DocumentProcessorService_CreateProcessor_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_v1 + + +async def sample_create_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_CreateProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py new file mode 100644 index 00000000..91e1a877 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_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 CreateProcessor +# 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_v1_generated_DocumentProcessorService_CreateProcessor_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_v1 + + +def sample_create_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_CreateProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py new file mode 100644 index 00000000..e72258a3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_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 DeleteProcessor +# 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_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1 + + +async def sample_delete_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py new file mode 100644 index 00000000..62a97410 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_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 DeleteProcessor +# 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_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1 + + +def sample_delete_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py new file mode 100644 index 00000000..e760dbd7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_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 DeleteProcessorVersion +# 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_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1 + + +async def sample_delete_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py new file mode 100644 index 00000000..100535d0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_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 DeleteProcessorVersion +# 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_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1 + + +def sample_delete_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py new file mode 100644 index 00000000..af78c036 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_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 DeployProcessorVersion +# 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_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1 + + +async def sample_deploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py new file mode 100644 index 00000000..29e3b067 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_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 DeployProcessorVersion +# 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_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1 + + +def sample_deploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py new file mode 100644 index 00000000..17653881 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_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 DisableProcessor +# 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_v1_generated_DocumentProcessorService_DisableProcessor_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_v1 + + +async def sample_disable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DisableProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py new file mode 100644 index 00000000..b3465618 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_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 DisableProcessor +# 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_v1_generated_DocumentProcessorService_DisableProcessor_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_v1 + + +def sample_disable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_DisableProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py new file mode 100644 index 00000000..83554c7a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_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 EnableProcessor +# 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_v1_generated_DocumentProcessorService_EnableProcessor_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_v1 + + +async def sample_enable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_EnableProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py new file mode 100644 index 00000000..1070398b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_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 EnableProcessor +# 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_v1_generated_DocumentProcessorService_EnableProcessor_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_v1 + + +def sample_enable_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_EnableProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py new file mode 100644 index 00000000..76e24c04 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +async def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py new file mode 100644 index 00000000..33947155 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py new file mode 100644 index 00000000..2b317265 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_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 FetchProcessorTypes +# 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_v1_generated_DocumentProcessorService_FetchProcessorTypes_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_v1 + + +async def sample_fetch_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.fetch_processor_types(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_FetchProcessorTypes_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py new file mode 100644 index 00000000..8eb1f1e0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_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 FetchProcessorTypes +# 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_v1_generated_DocumentProcessorService_FetchProcessorTypes_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_v1 + + +def sample_fetch_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = client.fetch_processor_types(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_FetchProcessorTypes_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py new file mode 100644 index 00000000..f1391f01 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +async def sample_get_evaluation(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetEvaluation_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py new file mode 100644 index 00000000..ea4c1a33 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +def sample_get_evaluation(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetEvaluation_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py new file mode 100644 index 00000000..603d84b0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_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 GetProcessor +# 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_v1_generated_DocumentProcessorService_GetProcessor_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_v1 + + +async def sample_get_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py new file mode 100644 index 00000000..008ddd91 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_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 GetProcessor +# 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_v1_generated_DocumentProcessorService_GetProcessor_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_v1 + + +def sample_get_processor(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py new file mode 100644 index 00000000..20552d91 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_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 GetProcessorType +# 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_v1_generated_DocumentProcessorService_GetProcessorType_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_v1 + + +async def sample_get_processor_type(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_type(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetProcessorType_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py new file mode 100644 index 00000000..ad27f0c6 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_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 GetProcessorType +# 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_v1_generated_DocumentProcessorService_GetProcessorType_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_v1 + + +def sample_get_processor_type(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_type(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetProcessorType_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py new file mode 100644 index 00000000..c9c48239 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_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 GetProcessorVersion +# 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_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1 + + +async def sample_get_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_version(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py new file mode 100644 index 00000000..9e552ac2 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_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 GetProcessorVersion +# 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_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1 + + +def sample_get_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_version(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py new file mode 100644 index 00000000..a056d558 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +async def sample_list_evaluations(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1_generated_DocumentProcessorService_ListEvaluations_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py new file mode 100644 index 00000000..e377f0b9 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +def sample_list_evaluations(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1_generated_DocumentProcessorService_ListEvaluations_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py new file mode 100644 index 00000000..ebeab7d6 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_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 ListProcessorTypes +# 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_v1_generated_DocumentProcessorService_ListProcessorTypes_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_v1 + + +async def sample_list_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py new file mode 100644 index 00000000..ad015a1c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_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 ListProcessorTypes +# 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_v1_generated_DocumentProcessorService_ListProcessorTypes_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_v1 + + +def sample_list_processor_types(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py new file mode 100644 index 00000000..1772e854 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_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 ListProcessorVersions +# 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_v1_generated_DocumentProcessorService_ListProcessorVersions_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_v1 + + +async def sample_list_processor_versions(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py new file mode 100644 index 00000000..a7dc121c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_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 ListProcessorVersions +# 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_v1_generated_DocumentProcessorService_ListProcessorVersions_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_v1 + + +def sample_list_processor_versions(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py new file mode 100644 index 00000000..c90f095d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_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 ListProcessors +# 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_v1_generated_DocumentProcessorService_ListProcessors_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_v1 + + +async def sample_list_processors(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ListProcessors_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py new file mode 100644 index 00000000..f14d4676 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_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 ListProcessors +# 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_v1_generated_DocumentProcessorService_ListProcessors_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_v1 + + +def sample_list_processors(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ListProcessors_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py new file mode 100644 index 00000000..d5250da7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_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 ProcessDocument +# 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_v1_generated_DocumentProcessorService_ProcessDocument_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_v1 + + +async def sample_process_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = await client.process_document(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ProcessDocument_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py new file mode 100644 index 00000000..05ebfbb8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_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 ProcessDocument +# 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_v1_generated_DocumentProcessorService_ProcessDocument_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_v1 + + +def sample_process_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = client.process_document(request=request) + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ProcessDocument_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py new file mode 100644 index 00000000..cc3a8df1 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py @@ -0,0 +1,60 @@ +# -*- 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 ReviewDocument +# 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_v1_generated_DocumentProcessorService_ReviewDocument_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_v1 + + +async def sample_review_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ReviewDocument_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py new file mode 100644 index 00000000..845e5f0d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py @@ -0,0 +1,60 @@ +# -*- 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 ReviewDocument +# 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_v1_generated_DocumentProcessorService_ReviewDocument_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_v1 + + +def sample_review_document(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1.Document() + inline_document.uri = "uri_value" + + request = documentai_v1.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_ReviewDocument_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py new file mode 100644 index 00000000..97cfcb35 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py @@ -0,0 +1,57 @@ +# -*- 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 SetDefaultProcessorVersion +# 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_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_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_v1 + + +async def sample_set_default_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py new file mode 100644 index 00000000..838a5131 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py @@ -0,0 +1,57 @@ +# -*- 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 SetDefaultProcessorVersion +# 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_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_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_v1 + + +def sample_set_default_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py new file mode 100644 index 00000000..2a0d5adf --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +async def sample_train_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1_generated_DocumentProcessorService_TrainProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py new file mode 100644 index 00000000..8f4661bd --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_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_v1_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_v1 + + +def sample_train_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1_generated_DocumentProcessorService_TrainProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py new file mode 100644 index 00000000..b25557e8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_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 UndeployProcessorVersion +# 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_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1 + + +async def sample_undeploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py new file mode 100644 index 00000000..3e75efe3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_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 UndeployProcessorVersion +# 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_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1 + + +def sample_undeploy_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json new file mode 100644 index 00000000..96d60af2 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json @@ -0,0 +1,3549 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.documentai.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-documentai", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.batch_process_documents", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "BatchProcessDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.BatchProcessRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "batch_process_documents" + }, + "description": "Sample for BatchProcessDocuments", + "file": "documentai_v1_generated_document_processor_service_batch_process_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1_generated_document_processor_service_batch_process_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.batch_process_documents", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "BatchProcessDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.BatchProcessRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "batch_process_documents" + }, + "description": "Sample for BatchProcessDocuments", + "file": "documentai_v1_generated_document_processor_service_batch_process_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1_generated_document_processor_service_batch_process_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.create_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.documentai_v1.types.Processor" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1.types.Processor", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "documentai_v1_generated_document_processor_service_create_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_CreateProcessor_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_v1_generated_document_processor_service_create_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.create_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.documentai_v1.types.Processor" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1.types.Processor", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "documentai_v1_generated_document_processor_service_create_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_CreateProcessor_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_v1_generated_document_processor_service_create_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.delete_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DeleteProcessorVersionRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_processor_version" + }, + "description": "Sample for DeleteProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_delete_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1_generated_document_processor_service_delete_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.delete_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DeleteProcessorVersionRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_processor_version" + }, + "description": "Sample for DeleteProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_delete_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1_generated_document_processor_service_delete_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.delete_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DeleteProcessorRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "documentai_v1_generated_document_processor_service_delete_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1_generated_document_processor_service_delete_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.delete_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DeleteProcessorRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "documentai_v1_generated_document_processor_service_delete_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1_generated_document_processor_service_delete_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.deploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DeployProcessorVersionRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "deploy_processor_version" + }, + "description": "Sample for DeployProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_deploy_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1_generated_document_processor_service_deploy_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.deploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DeployProcessorVersionRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "deploy_processor_version" + }, + "description": "Sample for DeployProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1_generated_document_processor_service_deploy_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.disable_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DisableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DisableProcessorRequest" + }, + { + "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": "disable_processor" + }, + "description": "Sample for DisableProcessor", + "file": "documentai_v1_generated_document_processor_service_disable_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DisableProcessor_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_v1_generated_document_processor_service_disable_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.disable_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DisableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.DisableProcessorRequest" + }, + { + "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": "disable_processor" + }, + "description": "Sample for DisableProcessor", + "file": "documentai_v1_generated_document_processor_service_disable_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_DisableProcessor_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_v1_generated_document_processor_service_disable_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.enable_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EnableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.EnableProcessorRequest" + }, + { + "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": "enable_processor" + }, + "description": "Sample for EnableProcessor", + "file": "documentai_v1_generated_document_processor_service_enable_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_EnableProcessor_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_v1_generated_document_processor_service_enable_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.enable_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EnableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.EnableProcessorRequest" + }, + { + "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": "enable_processor" + }, + "description": "Sample for EnableProcessor", + "file": "documentai_v1_generated_document_processor_service_enable_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_EnableProcessor_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_v1_generated_document_processor_service_enable_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.evaluate_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EvaluateProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_evaluate_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_evaluate_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.evaluate_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EvaluateProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_evaluate_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_evaluate_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.fetch_processor_types", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "FetchProcessorTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.FetchProcessorTypesResponse", + "shortName": "fetch_processor_types" + }, + "description": "Sample for FetchProcessorTypes", + "file": "documentai_v1_generated_document_processor_service_fetch_processor_types_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_fetch_processor_types_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.fetch_processor_types", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "FetchProcessorTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.FetchProcessorTypesResponse", + "shortName": "fetch_processor_types" + }, + "description": "Sample for FetchProcessorTypes", + "file": "documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_fetch_processor_types_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_evaluation", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "documentai_v1_generated_document_processor_service_get_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_get_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_evaluation", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "documentai_v1_generated_document_processor_service_get_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_get_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_type", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" + }, + { + "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_v1.types.ProcessorType", + "shortName": "get_processor_type" + }, + "description": "Sample for GetProcessorType", + "file": "documentai_v1_generated_document_processor_service_get_processor_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_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_v1_generated_document_processor_service_get_processor_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_type", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" + }, + { + "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_v1.types.ProcessorType", + "shortName": "get_processor_type" + }, + "description": "Sample for GetProcessorType", + "file": "documentai_v1_generated_document_processor_service_get_processor_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_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_v1_generated_document_processor_service_get_processor_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.ProcessorVersion", + "shortName": "get_processor_version" + }, + "description": "Sample for GetProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_get_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1_generated_document_processor_service_get_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.ProcessorVersion", + "shortName": "get_processor_version" + }, + "description": "Sample for GetProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1_generated_document_processor_service_get_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.GetProcessorRequest" + }, + { + "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_v1.types.Processor", + "shortName": "get_processor" + }, + "description": "Sample for GetProcessor", + "file": "documentai_v1_generated_document_processor_service_get_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_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_v1_generated_document_processor_service_get_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.GetProcessorRequest" + }, + { + "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_v1.types.Processor", + "shortName": "get_processor" + }, + "description": "Sample for GetProcessor", + "file": "documentai_v1_generated_document_processor_service_get_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_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_v1_generated_document_processor_service_get_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_evaluations", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" + }, + "description": "Sample for ListEvaluations", + "file": "documentai_v1_generated_document_processor_service_list_evaluations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_evaluations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_evaluations", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" + }, + "description": "Sample for ListEvaluations", + "file": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processor_types", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListProcessorTypesRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListProcessorTypesAsyncPager", + "shortName": "list_processor_types" + }, + "description": "Sample for ListProcessorTypes", + "file": "documentai_v1_generated_document_processor_service_list_processor_types_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_processor_types_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processor_types", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListProcessorTypesRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListProcessorTypesPager", + "shortName": "list_processor_types" + }, + "description": "Sample for ListProcessorTypes", + "file": "documentai_v1_generated_document_processor_service_list_processor_types_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_processor_types_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processor_versions", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListProcessorVersionsRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager", + "shortName": "list_processor_versions" + }, + "description": "Sample for ListProcessorVersions", + "file": "documentai_v1_generated_document_processor_service_list_processor_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_processor_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processor_versions", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListProcessorVersionsRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListProcessorVersionsPager", + "shortName": "list_processor_versions" + }, + "description": "Sample for ListProcessorVersions", + "file": "documentai_v1_generated_document_processor_service_list_processor_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_processor_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processors", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessors", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListProcessorsRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListProcessorsAsyncPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "documentai_v1_generated_document_processor_service_list_processors_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessors_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_processors_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processors", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessors", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ListProcessorsRequest" + }, + { + "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_v1.services.document_processor_service.pagers.ListProcessorsPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "documentai_v1_generated_document_processor_service_list_processors_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessors_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_list_processors_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.process_document", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ProcessDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ProcessRequest" + }, + { + "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_v1.types.ProcessResponse", + "shortName": "process_document" + }, + "description": "Sample for ProcessDocument", + "file": "documentai_v1_generated_document_processor_service_process_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ProcessDocument_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_process_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.process_document", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ProcessDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ProcessRequest" + }, + { + "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_v1.types.ProcessResponse", + "shortName": "process_document" + }, + "description": "Sample for ProcessDocument", + "file": "documentai_v1_generated_document_processor_service_process_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ProcessDocument_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_process_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.review_document", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ReviewDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ReviewDocumentRequest" + }, + { + "name": "human_review_config", + "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": "review_document" + }, + "description": "Sample for ReviewDocument", + "file": "documentai_v1_generated_document_processor_service_review_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ReviewDocument_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_review_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.review_document", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ReviewDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.ReviewDocumentRequest" + }, + { + "name": "human_review_config", + "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": "review_document" + }, + "description": "Sample for ReviewDocument", + "file": "documentai_v1_generated_document_processor_service_review_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ReviewDocument_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_review_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.set_default_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "SetDefaultProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest" + }, + { + "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": "set_default_processor_version" + }, + "description": "Sample for SetDefaultProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_set_default_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_set_default_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.set_default_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "SetDefaultProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest" + }, + { + "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": "set_default_processor_version" + }, + "description": "Sample for SetDefaultProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.train_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "TrainProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor_version", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_train_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_train_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.train_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "TrainProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor_version", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_train_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_train_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.undeploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "UndeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.UndeployProcessorVersionRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "undeploy_processor_version" + }, + "description": "Sample for UndeployProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1_generated_document_processor_service_undeploy_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.undeploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "UndeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.UndeployProcessorVersionRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "undeploy_processor_version" + }, + "description": "Sample for UndeployProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1_generated_document_processor_service_undeploy_processor_version_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py new file mode 100644 index 00000000..090486ac --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py @@ -0,0 +1,197 @@ +#! /usr/bin/env python3 +# -*- 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. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class documentaiCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_process_documents': ('name', 'input_documents', 'document_output_config', 'skip_human_review', ), + 'create_processor': ('parent', 'processor', ), + 'delete_processor': ('name', ), + 'delete_processor_version': ('name', ), + '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_type': ('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', 'skip_human_review', 'field_mask', ), + 'review_document': ('human_review_config', 'inline_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', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=documentaiCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the documentai client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 00000000..ad9dc616 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,91 @@ +# -*- 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. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-documentai' + + +description = "Google Cloud Documentai API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + 'google-cloud-documentai >= 1.2.1, < 3.0.0dev', +] +url = "https://github.com/googleapis/python-documentai" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt new file mode 100644 index 00000000..45ffc899 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt new file mode 100644 index 00000000..45ffc899 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt new file mode 100644 index 00000000..45ffc899 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt new file mode 100644 index 00000000..e5a2433f --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +google-cloud-documentai==1.2.1 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt new file mode 100644 index 00000000..45ffc899 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt new file mode 100644 index 00000000..45ffc899 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-cloud-documentai diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py b/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py new file mode 100644 index 00000000..703be1f6 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py @@ -0,0 +1,13252 @@ +# -*- 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. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.documentai_v1.services.document_processor_service import DocumentProcessorServiceAsyncClient +from google.cloud.documentai_v1.services.document_processor_service import DocumentProcessorServiceClient +from google.cloud.documentai_v1.services.document_processor_service import pagers +from google.cloud.documentai_v1.services.document_processor_service import transports +from google.cloud.documentai_v1.types import barcode +from google.cloud.documentai_v1.types import document +from google.cloud.documentai_v1.types import document_io +from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import document_schema +from google.cloud.documentai_v1.types import evaluation +from google.cloud.documentai_v1.types import geometry +from google.cloud.documentai_v1.types import processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.documentai_v1.types import processor_type +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from google.type import money_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(None) is None + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentProcessorServiceClient, "grpc"), + (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), + (DocumentProcessorServiceClient, "rest"), +]) +def test_document_processor_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'documentai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://documentai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DocumentProcessorServiceRestTransport, "rest"), +]) +def test_document_processor_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentProcessorServiceClient, "grpc"), + (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), + (DocumentProcessorServiceClient, "rest"), +]) +def test_document_processor_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'documentai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://documentai.googleapis.com' + ) + + +def test_document_processor_service_client_get_transport_class(): + transport = DocumentProcessorServiceClient.get_transport_class() + available_transports = [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceRestTransport, + ] + assert transport in available_transports + + transport = DocumentProcessorServiceClient.get_transport_class("grpc") + assert transport == transports.DocumentProcessorServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), +]) +@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) +@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) +def test_document_processor_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "true"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "false"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "true"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) +@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_document_processor_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DocumentProcessorServiceClient, DocumentProcessorServiceAsyncClient +]) +@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) +@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) +def test_document_processor_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), +]) +def test_document_processor_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", None), +]) +def test_document_processor_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_document_processor_service_client_client_options_from_dict(): + with mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentProcessorServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_document_processor_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "documentai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="documentai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ProcessRequest, + dict, +]) +def test_process_document(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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ProcessResponse( + ) + response = client.process_document(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.ProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.ProcessResponse) + + +def test_process_document_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.process_document), + '__call__') as call: + client.process_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ProcessRequest() + +@pytest.mark.asyncio +async def test_process_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ProcessRequest): + 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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse( + )) + response = await client.process_document(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.ProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.ProcessResponse) + + +@pytest.mark.asyncio +async def test_process_document_async_from_dict(): + await test_process_document_async(request_type=dict) + + +def test_process_document_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.ProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.process_document), + '__call__') as call: + call.return_value = document_processor_service.ProcessResponse() + client.process_document(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_process_document_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.ProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.process_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) + await client.process_document(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_process_document_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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ProcessResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.process_document( + 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_process_document_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.process_document( + document_processor_service.ProcessRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_process_document_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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ProcessResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.process_document( + 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_process_document_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.process_document( + document_processor_service.ProcessRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.BatchProcessRequest, + dict, +]) +def test_batch_process_documents(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.batch_process_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_process_documents(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.BatchProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_process_documents_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.batch_process_documents), + '__call__') as call: + client.batch_process_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.BatchProcessRequest() + +@pytest.mark.asyncio +async def test_batch_process_documents_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.BatchProcessRequest): + 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.batch_process_documents), + '__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.batch_process_documents(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.BatchProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_process_documents_async_from_dict(): + await test_batch_process_documents_async(request_type=dict) + + +def test_batch_process_documents_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.BatchProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_process_documents(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_batch_process_documents_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.BatchProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_process_documents(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_batch_process_documents_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.batch_process_documents), + '__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.batch_process_documents( + 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_batch_process_documents_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.batch_process_documents( + document_processor_service.BatchProcessRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_batch_process_documents_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.batch_process_documents), + '__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.batch_process_documents( + 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_batch_process_documents_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.batch_process_documents( + document_processor_service.BatchProcessRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.FetchProcessorTypesRequest, + dict, +]) +def test_fetch_processor_types(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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.FetchProcessorTypesResponse( + ) + response = client.fetch_processor_types(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.FetchProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) + + +def test_fetch_processor_types_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.fetch_processor_types), + '__call__') as call: + client.fetch_processor_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.FetchProcessorTypesRequest() + +@pytest.mark.asyncio +async def test_fetch_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.FetchProcessorTypesRequest): + 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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse( + )) + response = await client.fetch_processor_types(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.FetchProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) + + +@pytest.mark.asyncio +async def test_fetch_processor_types_async_from_dict(): + await test_fetch_processor_types_async(request_type=dict) + + +def test_fetch_processor_types_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.FetchProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_processor_types), + '__call__') as call: + call.return_value = document_processor_service.FetchProcessorTypesResponse() + client.fetch_processor_types(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_fetch_processor_types_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.FetchProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_processor_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) + await client.fetch_processor_types(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_fetch_processor_types_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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.FetchProcessorTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_processor_types( + 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_fetch_processor_types_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.fetch_processor_types( + document_processor_service.FetchProcessorTypesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_fetch_processor_types_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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.FetchProcessorTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_processor_types( + 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_fetch_processor_types_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.fetch_processor_types( + document_processor_service.FetchProcessorTypesRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorTypesRequest, + dict, +]) +def test_list_processor_types(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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorTypesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_processor_types(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.ListProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_types_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_processor_types), + '__call__') as call: + client.list_processor_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListProcessorTypesRequest() + +@pytest.mark.asyncio +async def test_list_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorTypesRequest): + 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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_processor_types(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.ListProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorTypesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_processor_types_async_from_dict(): + await test_list_processor_types_async(request_type=dict) + + +def test_list_processor_types_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.ListProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_types), + '__call__') as call: + call.return_value = document_processor_service.ListProcessorTypesResponse() + client.list_processor_types(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_processor_types_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.ListProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) + await client.list_processor_types(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_processor_types_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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processor_types( + 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_processor_types_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_processor_types( + document_processor_service.ListProcessorTypesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processor_types_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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processor_types( + 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_processor_types_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_processor_types( + document_processor_service.ListProcessorTypesRequest(), + parent='parent_value', + ) + + +def test_list_processor_types_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_processor_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processor_types(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor_type.ProcessorType) + for i in results) +def test_list_processor_types_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_processor_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processor_types(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_processor_types_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_processor_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processor_types(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, processor_type.ProcessorType) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processor_types_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_processor_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_processor_types(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 + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorTypeRequest, + dict, +]) +def test_get_processor_type(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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor_type.ProcessorType( + name='name_value', + type_='type__value', + category='category_value', + allow_creation=True, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + sample_document_uris=['sample_document_uris_value'], + ) + response = client.get_processor_type(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.GetProcessorTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor_type.ProcessorType) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.category == 'category_value' + assert response.allow_creation is True + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.sample_document_uris == ['sample_document_uris_value'] + + +def test_get_processor_type_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_processor_type), + '__call__') as call: + client.get_processor_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetProcessorTypeRequest() + +@pytest.mark.asyncio +async def test_get_processor_type_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorTypeRequest): + 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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType( + name='name_value', + type_='type__value', + category='category_value', + allow_creation=True, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + sample_document_uris=['sample_document_uris_value'], + )) + response = await client.get_processor_type(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.GetProcessorTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor_type.ProcessorType) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.category == 'category_value' + assert response.allow_creation is True + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.sample_document_uris == ['sample_document_uris_value'] + + +@pytest.mark.asyncio +async def test_get_processor_type_async_from_dict(): + await test_get_processor_type_async(request_type=dict) + + +def test_get_processor_type_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.GetProcessorTypeRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_type), + '__call__') as call: + call.return_value = processor_type.ProcessorType() + client.get_processor_type(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_processor_type_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.GetProcessorTypeRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) + await client.get_processor_type(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_processor_type_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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor_type.ProcessorType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor_type( + 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_processor_type_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_processor_type( + document_processor_service.GetProcessorTypeRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_processor_type_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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor_type.ProcessorType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor_type( + 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_processor_type_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_processor_type( + document_processor_service.GetProcessorTypeRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorsRequest, + dict, +]) +def test_list_processors(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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_processors(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.ListProcessorsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processors_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_processors), + '__call__') as call: + client.list_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListProcessorsRequest() + +@pytest.mark.asyncio +async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorsRequest): + 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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_processors(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.ListProcessorsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_processors_async_from_dict(): + await test_list_processors_async(request_type=dict) + + +def test_list_processors_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.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = document_processor_service.ListProcessorsResponse() + client.list_processors(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_processors_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.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) + await client.list_processors(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_processors_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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processors( + 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_processors_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_processors( + document_processor_service.ListProcessorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processors_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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processors( + 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_processors_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_processors( + document_processor_service.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_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_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processors(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.Processor) + for i in results) +def test_list_processors_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_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processors(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_processors_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_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processors(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, processor.Processor) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processors_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_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_processors(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 + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorRequest, + dict, +]) +def test_get_processor(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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + response = client.get_processor(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.GetProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_get_processor_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_processor), + '__call__') as call: + client.get_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetProcessorRequest() + +@pytest.mark.asyncio +async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorRequest): + 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + )) + response = await client.get_processor(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.GetProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +@pytest.mark.asyncio +async def test_get_processor_async_from_dict(): + await test_get_processor_async(request_type=dict) + + +def test_get_processor_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.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = processor.Processor() + client.get_processor(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_processor_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.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) + await client.get_processor(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_processor_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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.Processor() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor( + 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_processor_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_processor( + document_processor_service.GetProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_processor_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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.Processor() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor( + 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_processor_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_processor( + document_processor_service.GetProcessorRequest(), + name='name_value', + ) + + +@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", [ + document_processor_service.GetProcessorVersionRequest, + dict, +]) +def test_get_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.get_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.ProcessorVersion( + name='name_value', + display_name='display_name_value', + state=processor.ProcessorVersion.State.DEPLOYED, + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + google_managed=True, + ) + response = client.get_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.GetProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.ProcessorVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == processor.ProcessorVersion.State.DEPLOYED + assert response.kms_key_name == 'kms_key_name_value' + assert response.kms_key_version_name == 'kms_key_version_name_value' + assert response.google_managed is True + + +def test_get_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.get_processor_version), + '__call__') as call: + client.get_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_get_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorVersionRequest): + 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_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion( + name='name_value', + display_name='display_name_value', + state=processor.ProcessorVersion.State.DEPLOYED, + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + google_managed=True, + )) + response = await client.get_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.GetProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.ProcessorVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == processor.ProcessorVersion.State.DEPLOYED + assert response.kms_key_name == 'kms_key_name_value' + assert response.kms_key_version_name == 'kms_key_version_name_value' + assert response.google_managed is True + + +@pytest.mark.asyncio +async def test_get_processor_version_async_from_dict(): + await test_get_processor_version_async(request_type=dict) + + +def test_get_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.GetProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_version), + '__call__') as call: + call.return_value = processor.ProcessorVersion() + client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_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.GetProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) + await client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_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.get_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.ProcessorVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor_version( + 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_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.get_processor_version( + document_processor_service.GetProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_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.get_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.ProcessorVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor_version( + 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_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.get_processor_version( + document_processor_service.GetProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorVersionsRequest, + dict, +]) +def test_list_processor_versions(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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_processor_versions(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.ListProcessorVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_versions_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_processor_versions), + '__call__') as call: + client.list_processor_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListProcessorVersionsRequest() + +@pytest.mark.asyncio +async def test_list_processor_versions_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorVersionsRequest): + 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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_processor_versions(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.ListProcessorVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_processor_versions_async_from_dict(): + await test_list_processor_versions_async(request_type=dict) + + +def test_list_processor_versions_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.ListProcessorVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_versions), + '__call__') as call: + call.return_value = document_processor_service.ListProcessorVersionsResponse() + client.list_processor_versions(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_processor_versions_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.ListProcessorVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) + await client.list_processor_versions(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_processor_versions_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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processor_versions( + 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_processor_versions_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_processor_versions( + document_processor_service.ListProcessorVersionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processor_versions_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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processor_versions( + 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_processor_versions_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_processor_versions( + document_processor_service.ListProcessorVersionsRequest(), + parent='parent_value', + ) + + +def test_list_processor_versions_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_processor_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processor_versions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.ProcessorVersion) + for i in results) +def test_list_processor_versions_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_processor_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processor_versions(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_processor_versions_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_processor_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processor_versions(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, processor.ProcessorVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processor_versions_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_processor_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_processor_versions(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 + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorVersionRequest, + dict, +]) +def test_delete_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.delete_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_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.DeleteProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_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.delete_processor_version), + '__call__') as call: + client.delete_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DeleteProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_delete_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorVersionRequest): + 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.delete_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.delete_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.DeleteProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_processor_version_async_from_dict(): + await test_delete_processor_version_async(request_type=dict) + + +def test_delete_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.DeleteProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_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.DeleteProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_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.delete_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.delete_processor_version( + 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_delete_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.delete_processor_version( + document_processor_service.DeleteProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_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.delete_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.delete_processor_version( + 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_delete_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.delete_processor_version( + document_processor_service.DeleteProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeployProcessorVersionRequest, + dict, +]) +def test_deploy_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.deploy_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.deploy_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.DeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_deploy_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.deploy_processor_version), + '__call__') as call: + client.deploy_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DeployProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_deploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeployProcessorVersionRequest): + 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.deploy_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.deploy_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.DeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_deploy_processor_version_async_from_dict(): + await test_deploy_processor_version_async(request_type=dict) + + +def test_deploy_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.DeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.deploy_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_deploy_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.DeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.deploy_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_deploy_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.deploy_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.deploy_processor_version( + 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_deploy_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.deploy_processor_version( + document_processor_service.DeployProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_deploy_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.deploy_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.deploy_processor_version( + 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_deploy_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.deploy_processor_version( + document_processor_service.DeployProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.UndeployProcessorVersionRequest, + dict, +]) +def test_undeploy_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.undeploy_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.undeploy_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.UndeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_undeploy_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.undeploy_processor_version), + '__call__') as call: + client.undeploy_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.UndeployProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_undeploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.UndeployProcessorVersionRequest): + 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.undeploy_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.undeploy_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.UndeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_undeploy_processor_version_async_from_dict(): + await test_undeploy_processor_version_async(request_type=dict) + + +def test_undeploy_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.UndeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.undeploy_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_undeploy_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.UndeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.undeploy_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_undeploy_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.undeploy_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.undeploy_processor_version( + 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_undeploy_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.undeploy_processor_version( + document_processor_service.UndeployProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_undeploy_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.undeploy_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.undeploy_processor_version( + 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_undeploy_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.undeploy_processor_version( + document_processor_service.UndeployProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.CreateProcessorRequest, + dict, +]) +def test_create_processor(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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=gcd_processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + response = client.create_processor(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.CreateProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == gcd_processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_create_processor_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.create_processor), + '__call__') as call: + client.create_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.CreateProcessorRequest() + +@pytest.mark.asyncio +async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.CreateProcessorRequest): + 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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=gcd_processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + )) + response = await client.create_processor(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.CreateProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == gcd_processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +@pytest.mark.asyncio +async def test_create_processor_async_from_dict(): + await test_create_processor_async(request_type=dict) + + +def test_create_processor_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.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = gcd_processor.Processor() + client.create_processor(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_create_processor_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.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) + await client.create_processor(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_create_processor_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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_processor.Processor() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_processor( + parent='parent_value', + processor=gcd_processor.Processor(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 + mock_val = gcd_processor.Processor(name='name_value') + assert arg == mock_val + + +def test_create_processor_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.create_processor( + document_processor_service.CreateProcessorRequest(), + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_processor_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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_processor.Processor() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_processor( + parent='parent_value', + processor=gcd_processor.Processor(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 + mock_val = gcd_processor.Processor(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_processor_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.create_processor( + document_processor_service.CreateProcessorRequest(), + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorRequest, + dict, +]) +def test_delete_processor(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.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_processor(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.DeleteProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_processor_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.delete_processor), + '__call__') as call: + client.delete_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DeleteProcessorRequest() + +@pytest.mark.asyncio +async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorRequest): + 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.delete_processor), + '__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.delete_processor(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.DeleteProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_processor_async_from_dict(): + await test_delete_processor_async(request_type=dict) + + +def test_delete_processor_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.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_processor(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_delete_processor_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.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_processor(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_delete_processor_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.delete_processor), + '__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.delete_processor( + 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_delete_processor_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.delete_processor( + document_processor_service.DeleteProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_processor_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.delete_processor), + '__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.delete_processor( + 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_delete_processor_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.delete_processor( + document_processor_service.DeleteProcessorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.EnableProcessorRequest, + dict, +]) +def test_enable_processor(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.enable_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.enable_processor(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.EnableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_enable_processor_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.enable_processor), + '__call__') as call: + client.enable_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.EnableProcessorRequest() + +@pytest.mark.asyncio +async def test_enable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EnableProcessorRequest): + 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.enable_processor), + '__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.enable_processor(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.EnableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_enable_processor_async_from_dict(): + await test_enable_processor_async(request_type=dict) + + +def test_enable_processor_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.EnableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.enable_processor(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_enable_processor_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.EnableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.enable_processor(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'] + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DisableProcessorRequest, + dict, +]) +def test_disable_processor(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.disable_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.disable_processor(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.DisableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_disable_processor_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.disable_processor), + '__call__') as call: + client.disable_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DisableProcessorRequest() + +@pytest.mark.asyncio +async def test_disable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DisableProcessorRequest): + 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.disable_processor), + '__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.disable_processor(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.DisableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_disable_processor_async_from_dict(): + await test_disable_processor_async(request_type=dict) + + +def test_disable_processor_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.DisableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.disable_processor(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_disable_processor_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.DisableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.disable_processor(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'] + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.SetDefaultProcessorVersionRequest, + dict, +]) +def test_set_default_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.set_default_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_default_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.SetDefaultProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_default_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.set_default_processor_version), + '__call__') as call: + client.set_default_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_set_default_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.SetDefaultProcessorVersionRequest): + 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.set_default_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.set_default_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.SetDefaultProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_default_processor_version_async_from_dict(): + await test_set_default_processor_version_async(request_type=dict) + + +def test_set_default_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.SetDefaultProcessorVersionRequest() + + request.processor = 'processor_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_default_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=processor_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_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.SetDefaultProcessorVersionRequest() + + request.processor = 'processor_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_default_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=processor_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ReviewDocumentRequest, + dict, +]) +def test_review_document(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.review_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.review_document(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.ReviewDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_review_document_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.review_document), + '__call__') as call: + client.review_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ReviewDocumentRequest() + +@pytest.mark.asyncio +async def test_review_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ReviewDocumentRequest): + 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.review_document), + '__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.review_document(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.ReviewDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_review_document_async_from_dict(): + await test_review_document_async(request_type=dict) + + +def test_review_document_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.ReviewDocumentRequest() + + request.human_review_config = 'human_review_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.review_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.review_document(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', + 'human_review_config=human_review_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_review_document_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.ReviewDocumentRequest() + + request.human_review_config = 'human_review_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.review_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.review_document(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', + 'human_review_config=human_review_config_value', + ) in kw['metadata'] + + +def test_review_document_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.review_document), + '__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.review_document( + human_review_config='human_review_config_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].human_review_config + mock_val = 'human_review_config_value' + assert arg == mock_val + + +def test_review_document_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.review_document( + document_processor_service.ReviewDocumentRequest(), + human_review_config='human_review_config_value', + ) + +@pytest.mark.asyncio +async def test_review_document_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.review_document), + '__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.review_document( + human_review_config='human_review_config_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].human_review_config + mock_val = 'human_review_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_review_document_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.review_document( + document_processor_service.ReviewDocumentRequest(), + human_review_config='human_review_config_value', + ) + + +@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, + ) + + # 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 = 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', + ) + + # 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 + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ProcessRequest, + dict, +]) +def test_process_document_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.process_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.ProcessResponse) + + +def test_process_document_rest_required_fields(request_type=document_processor_service.ProcessRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.process_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_process_document_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.process_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_process_document_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_process_document") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_process_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ProcessRequest.pb(document_processor_service.ProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ProcessResponse.to_json(document_processor_service.ProcessResponse()) + + request = document_processor_service.ProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ProcessResponse() + + client.process_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_process_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ProcessRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.process_document(request) + + +def test_process_document_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.process_document(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}:process" % client.transport._host, args[1]) + + +def test_process_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.process_document( + document_processor_service.ProcessRequest(), + name='name_value', + ) + + +def test_process_document_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.BatchProcessRequest, + dict, +]) +def test_batch_process_documents_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_process_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_process_documents_rest_required_fields(request_type=document_processor_service.BatchProcessRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_process_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_process_documents_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_process_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_process_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_batch_process_documents") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_batch_process_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.BatchProcessRequest.pb(document_processor_service.BatchProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.BatchProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_process_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_process_documents_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.BatchProcessRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_process_documents(request) + + +def test_batch_process_documents_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.batch_process_documents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}:batchProcess" % client.transport._host, args[1]) + + +def test_batch_process_documents_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_process_documents( + document_processor_service.BatchProcessRequest(), + name='name_value', + ) + + +def test_batch_process_documents_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.FetchProcessorTypesRequest, + dict, +]) +def test_fetch_processor_types_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.fetch_processor_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) + + +def test_fetch_processor_types_rest_required_fields(request_type=document_processor_service.FetchProcessorTypesRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.fetch_processor_types(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_processor_types_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_processor_types_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.FetchProcessorTypesRequest.pb(document_processor_service.FetchProcessorTypesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.FetchProcessorTypesResponse.to_json(document_processor_service.FetchProcessorTypesResponse()) + + request = document_processor_service.FetchProcessorTypesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.FetchProcessorTypesResponse() + + client.fetch_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.FetchProcessorTypesRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_processor_types(request) + + +def test_fetch_processor_types_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.fetch_processor_types(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}:fetchProcessorTypes" % client.transport._host, args[1]) + + +def test_fetch_processor_types_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_processor_types( + document_processor_service.FetchProcessorTypesRequest(), + parent='parent_value', + ) + + +def test_fetch_processor_types_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorTypesRequest, + dict, +]) +def test_list_processor_types_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processor_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_types_rest_required_fields(request_type=document_processor_service.ListProcessorTypesRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processor_types(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processor_types_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processor_types._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processor_types_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListProcessorTypesRequest.pb(document_processor_service.ListProcessorTypesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListProcessorTypesResponse.to_json(document_processor_service.ListProcessorTypesResponse()) + + request = document_processor_service.ListProcessorTypesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListProcessorTypesResponse() + + client.list_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorTypesRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processor_types(request) + + +def test_list_processor_types_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processor_types(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processorTypes" % client.transport._host, args[1]) + + +def test_list_processor_types_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processor_types( + document_processor_service.ListProcessorTypesRequest(), + parent='parent_value', + ) + + +def test_list_processor_types_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListProcessorTypesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_processor_types(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor_type.ProcessorType) + for i in results) + + pages = list(client.list_processor_types(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorTypeRequest, + dict, +]) +def test_get_processor_type_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor_type.ProcessorType( + name='name_value', + type_='type__value', + category='category_value', + allow_creation=True, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + sample_document_uris=['sample_document_uris_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor_type.ProcessorType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, processor_type.ProcessorType) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.category == 'category_value' + assert response.allow_creation is True + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.sample_document_uris == ['sample_document_uris_value'] + + +def test_get_processor_type_rest_required_fields(request_type=document_processor_service.GetProcessorTypeRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = processor_type.ProcessorType() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = processor_type.ProcessorType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor_type(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_type_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor_type._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_type_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetProcessorTypeRequest.pb(document_processor_service.GetProcessorTypeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = processor_type.ProcessorType.to_json(processor_type.ProcessorType()) + + request = document_processor_service.GetProcessorTypeRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = processor_type.ProcessorType() + + client.get_processor_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_type_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorTypeRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor_type(request) + + +def test_get_processor_type_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor_type.ProcessorType() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor_type.ProcessorType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor_type(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processorTypes/*}" % client.transport._host, args[1]) + + +def test_get_processor_type_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor_type( + document_processor_service.GetProcessorTypeRequest(), + name='name_value', + ) + + +def test_get_processor_type_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorsRequest, + dict, +]) +def test_list_processors_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processors_rest_required_fields(request_type=document_processor_service.ListProcessorsRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processors(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processors_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processors._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processors_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processors") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListProcessorsRequest.pb(document_processor_service.ListProcessorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListProcessorsResponse.to_json(document_processor_service.ListProcessorsResponse()) + + request = document_processor_service.ListProcessorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListProcessorsResponse() + + client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processors(request) + + +def test_list_processors_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processors(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_list_processors_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processors( + document_processor_service.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListProcessorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_processors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.Processor) + for i in results) + + pages = list(client.list_processors(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorRequest, + dict, +]) +def test_get_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_get_processor_rest_required_fields(request_type=document_processor_service.GetProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = processor.Processor() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetProcessorRequest.pb(document_processor_service.GetProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = processor.Processor.to_json(processor.Processor()) + + request = document_processor_service.GetProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = processor.Processor() + + client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor(request) + + +def test_get_processor_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.Processor() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_get_processor_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor( + document_processor_service.GetProcessorRequest(), + name='name_value', + ) + + +def test_get_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.TrainProcessorVersionRequest, + dict, +]) +def test_train_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.train_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_train_processor_version_rest_required_fields(request_type=document_processor_service.TrainProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.train_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_train_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.train_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "processorVersion", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_train_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_train_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_train_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.TrainProcessorVersionRequest.pb(document_processor_service.TrainProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.TrainProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.train_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_train_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.TrainProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.train_processor_version(request) + + +def test_train_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + processor_version=processor.ProcessorVersion(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.train_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train" % client.transport._host, args[1]) + + +def test_train_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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'), + ) + + +def test_train_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorVersionRequest, + dict, +]) +def test_get_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.ProcessorVersion( + name='name_value', + display_name='display_name_value', + state=processor.ProcessorVersion.State.DEPLOYED, + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + google_managed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.ProcessorVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.ProcessorVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == processor.ProcessorVersion.State.DEPLOYED + assert response.kms_key_name == 'kms_key_name_value' + assert response.kms_key_version_name == 'kms_key_version_name_value' + assert response.google_managed is True + + +def test_get_processor_version_rest_required_fields(request_type=document_processor_service.GetProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = processor.ProcessorVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = processor.ProcessorVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetProcessorVersionRequest.pb(document_processor_service.GetProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = processor.ProcessorVersion.to_json(processor.ProcessorVersion()) + + request = document_processor_service.GetProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = processor.ProcessorVersion() + + client.get_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor_version(request) + + +def test_get_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.ProcessorVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.ProcessorVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) + + +def test_get_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor_version( + document_processor_service.GetProcessorVersionRequest(), + name='name_value', + ) + + +def test_get_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorVersionsRequest, + dict, +]) +def test_list_processor_versions_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorVersionsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processor_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_versions_rest_required_fields(request_type=document_processor_service.ListProcessorVersionsRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processor_versions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processor_versions_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processor_versions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processor_versions_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_versions") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListProcessorVersionsRequest.pb(document_processor_service.ListProcessorVersionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListProcessorVersionsResponse.to_json(document_processor_service.ListProcessorVersionsResponse()) + + request = document_processor_service.ListProcessorVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListProcessorVersionsResponse() + + client.list_processor_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processor_versions_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorVersionsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processor_versions(request) + + +def test_list_processor_versions_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processor_versions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions" % client.transport._host, args[1]) + + +def test_list_processor_versions_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processor_versions( + document_processor_service.ListProcessorVersionsRequest(), + parent='parent_value', + ) + + +def test_list_processor_versions_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListProcessorVersionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + + pager = client.list_processor_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.ProcessorVersion) + for i in results) + + pages = list(client.list_processor_versions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorVersionRequest, + dict, +]) +def test_delete_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_processor_version_rest_required_fields(request_type=document_processor_service.DeleteProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DeleteProcessorVersionRequest.pb(document_processor_service.DeleteProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DeleteProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_processor_version(request) + + +def test_delete_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) + + +def test_delete_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_processor_version( + document_processor_service.DeleteProcessorVersionRequest(), + name='name_value', + ) + + +def test_delete_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeployProcessorVersionRequest, + dict, +]) +def test_deploy_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.deploy_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_deploy_processor_version_rest_required_fields(request_type=document_processor_service.DeployProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.deploy_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_deploy_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_deploy_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_deploy_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_deploy_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DeployProcessorVersionRequest.pb(document_processor_service.DeployProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DeployProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.deploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_deploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeployProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.deploy_processor_version(request) + + +def test_deploy_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.deploy_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" % client.transport._host, args[1]) + + +def test_deploy_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.deploy_processor_version( + document_processor_service.DeployProcessorVersionRequest(), + name='name_value', + ) + + +def test_deploy_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.UndeployProcessorVersionRequest, + dict, +]) +def test_undeploy_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.undeploy_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undeploy_processor_version_rest_required_fields(request_type=document_processor_service.UndeployProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.undeploy_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undeploy_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undeploy_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_undeploy_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_undeploy_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.UndeployProcessorVersionRequest.pb(document_processor_service.UndeployProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.UndeployProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undeploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undeploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.UndeployProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undeploy_processor_version(request) + + +def test_undeploy_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.undeploy_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" % client.transport._host, args[1]) + + +def test_undeploy_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undeploy_processor_version( + document_processor_service.UndeployProcessorVersionRequest(), + name='name_value', + ) + + +def test_undeploy_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.CreateProcessorRequest, + dict, +]) +def test_create_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=gcd_processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_processor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == gcd_processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_create_processor_rest_required_fields(request_type=document_processor_service.CreateProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_processor.Processor() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "processor", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_create_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.CreateProcessorRequest.pb(document_processor_service.CreateProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_processor.Processor.to_json(gcd_processor.Processor()) + + request = document_processor_service.CreateProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_processor.Processor() + + client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.CreateProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_processor(request) + + +def test_create_processor_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_processor.Processor() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_create_processor_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_processor( + document_processor_service.CreateProcessorRequest(), + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + + +def test_create_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorRequest, + dict, +]) +def test_delete_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_processor_rest_required_fields(request_type=document_processor_service.DeleteProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DeleteProcessorRequest.pb(document_processor_service.DeleteProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DeleteProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_processor(request) + + +def test_delete_processor_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_delete_processor_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_processor( + document_processor_service.DeleteProcessorRequest(), + name='name_value', + ) + + +def test_delete_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.EnableProcessorRequest, + dict, +]) +def test_enable_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.enable_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_enable_processor_rest_required_fields(request_type=document_processor_service.EnableProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.enable_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_enable_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.enable_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enable_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.EnableProcessorRequest.pb(document_processor_service.EnableProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.EnableProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.enable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_enable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EnableProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.enable_processor(request) + + +def test_enable_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DisableProcessorRequest, + dict, +]) +def test_disable_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.disable_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_disable_processor_rest_required_fields(request_type=document_processor_service.DisableProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.disable_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_disable_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.disable_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DisableProcessorRequest.pb(document_processor_service.DisableProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DisableProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.disable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_disable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DisableProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.disable_processor(request) + + +def test_disable_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.SetDefaultProcessorVersionRequest, + dict, +]) +def test_set_default_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_default_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_set_default_processor_version_rest_required_fields(request_type=document_processor_service.SetDefaultProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["processor"] = "" + request_init["default_processor_version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["processor"] = 'processor_value' + jsonified_request["defaultProcessorVersion"] = 'default_processor_version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "processor" in jsonified_request + assert jsonified_request["processor"] == 'processor_value' + assert "defaultProcessorVersion" in jsonified_request + assert jsonified_request["defaultProcessorVersion"] == 'default_processor_version_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_default_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_default_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_default_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("processor", "defaultProcessorVersion", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_default_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_set_default_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_set_default_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb(document_processor_service.SetDefaultProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.SetDefaultProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.set_default_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_default_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.SetDefaultProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_default_processor_version(request) + + +def test_set_default_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ReviewDocumentRequest, + dict, +]) +def test_review_document_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.review_document(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_review_document_rest_required_fields(request_type=document_processor_service.ReviewDocumentRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["human_review_config"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["humanReviewConfig"] = 'human_review_config_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "humanReviewConfig" in jsonified_request + assert jsonified_request["humanReviewConfig"] == 'human_review_config_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.review_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_review_document_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.review_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("humanReviewConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_review_document_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_review_document") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_review_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ReviewDocumentRequest.pb(document_processor_service.ReviewDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.ReviewDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.review_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_review_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ReviewDocumentRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.review_document(request) + + +def test_review_document_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} + + # get truthy value for each flattened field + mock_args = dict( + human_review_config='human_review_config_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.review_document(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" % client.transport._host, args[1]) + + +def test_review_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.review_document( + document_processor_service.ReviewDocumentRequest(), + human_review_config='human_review_config_value', + ) + + +def test_review_document_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.EvaluateProcessorVersionRequest, + dict, +]) +def test_evaluate_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.evaluate_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_evaluate_processor_version_rest_required_fields(request_type=document_processor_service.EvaluateProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["processor_version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["processorVersion"] = 'processor_version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "processorVersion" in jsonified_request + assert jsonified_request["processorVersion"] == 'processor_version_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.evaluate_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_evaluate_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.evaluate_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("processorVersion", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_evaluate_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_evaluate_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_evaluate_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.EvaluateProcessorVersionRequest.pb(document_processor_service.EvaluateProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.EvaluateProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.evaluate_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_evaluate_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EvaluateProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.evaluate_processor_version(request) + + +def test_evaluate_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + processor_version='processor_version_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.evaluate_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion" % client.transport._host, args[1]) + + +def test_evaluate_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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', + ) + + +def test_evaluate_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetEvaluationRequest, + dict, +]) +def test_get_evaluation_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation( + name='name_value', + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_evaluation(request) + + # 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_rest_required_fields(request_type=document_processor_service.GetEvaluationRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_evaluation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_evaluation_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_evaluation") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_evaluation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetEvaluationRequest.pb(document_processor_service.GetEvaluationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = evaluation.Evaluation.to_json(evaluation.Evaluation()) + + request = document_processor_service.GetEvaluationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.Evaluation() + + client.get_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_evaluation_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetEvaluationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_evaluation(request) + + +def test_get_evaluation_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}" % client.transport._host, args[1]) + + +def test_get_evaluation_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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', + ) + + +def test_get_evaluation_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListEvaluationsRequest, + dict, +]) +def test_list_evaluations_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListEvaluationsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_evaluations(request) + + # 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_rest_required_fields(request_type=document_processor_service.ListEvaluationsRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListEvaluationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_evaluations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_evaluations_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluations_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_evaluations") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_evaluations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListEvaluationsRequest.pb(document_processor_service.ListEvaluationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListEvaluationsResponse.to_json(document_processor_service.ListEvaluationsResponse()) + + request = document_processor_service.ListEvaluationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListEvaluationsResponse() + + client.list_evaluations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_evaluations_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListEvaluationsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_evaluations(request) + + +def test_list_evaluations_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListEvaluationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_evaluations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations" % client.transport._host, args[1]) + + +def test_list_evaluations_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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', + ) + + +def test_list_evaluations_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + 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(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListEvaluationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + pager = client.list_evaluations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) + for i in results) + + pages = list(client.list_evaluations(request=sample_request).pages) + 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( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentProcessorServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentProcessorServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentProcessorServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceGrpcAsyncIOTransport, + transports.DocumentProcessorServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DocumentProcessorServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentProcessorServiceGrpcTransport, + ) + +def test_document_processor_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentProcessorServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_document_processor_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentProcessorServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'process_document', + 'batch_process_documents', + 'fetch_processor_types', + 'list_processor_types', + 'get_processor_type', + 'list_processors', + 'get_processor', + 'train_processor_version', + 'get_processor_version', + 'list_processor_versions', + 'delete_processor_version', + 'deploy_processor_version', + 'undeploy_processor_version', + 'create_processor', + 'delete_processor', + 'enable_processor', + 'disable_processor', + 'set_default_processor_version', + 'review_document', + 'evaluate_processor_version', + 'get_evaluation', + 'list_evaluations', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_document_processor_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentProcessorServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_document_processor_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentProcessorServiceTransport() + adc.assert_called_once() + + +def test_document_processor_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentProcessorServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceGrpcAsyncIOTransport, + ], +) +def test_document_processor_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceGrpcAsyncIOTransport, + transports.DocumentProcessorServiceRestTransport, + ], +) +def test_document_processor_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentProcessorServiceGrpcTransport, grpc_helpers), + (transports.DocumentProcessorServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_document_processor_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "documentai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="documentai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) +def test_document_processor_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_document_processor_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.DocumentProcessorServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_document_processor_service_rest_lro_client(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_processor_service_host_no_port(transport_name): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'documentai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://documentai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_processor_service_host_with_port(transport_name): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'documentai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://documentai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_document_processor_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DocumentProcessorServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DocumentProcessorServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.process_document._session + session2 = client2.transport.process_document._session + assert session1 != session2 + session1 = client1.transport.batch_process_documents._session + session2 = client2.transport.batch_process_documents._session + assert session1 != session2 + session1 = client1.transport.fetch_processor_types._session + session2 = client2.transport.fetch_processor_types._session + assert session1 != session2 + session1 = client1.transport.list_processor_types._session + session2 = client2.transport.list_processor_types._session + assert session1 != session2 + session1 = client1.transport.get_processor_type._session + session2 = client2.transport.get_processor_type._session + assert session1 != session2 + session1 = client1.transport.list_processors._session + session2 = client2.transport.list_processors._session + assert session1 != session2 + session1 = client1.transport.get_processor._session + session2 = client2.transport.get_processor._session + assert session1 != session2 + session1 = client1.transport.train_processor_version._session + session2 = client2.transport.train_processor_version._session + assert session1 != session2 + session1 = client1.transport.get_processor_version._session + session2 = client2.transport.get_processor_version._session + assert session1 != session2 + session1 = client1.transport.list_processor_versions._session + session2 = client2.transport.list_processor_versions._session + assert session1 != session2 + session1 = client1.transport.delete_processor_version._session + session2 = client2.transport.delete_processor_version._session + assert session1 != session2 + session1 = client1.transport.deploy_processor_version._session + session2 = client2.transport.deploy_processor_version._session + assert session1 != session2 + session1 = client1.transport.undeploy_processor_version._session + session2 = client2.transport.undeploy_processor_version._session + assert session1 != session2 + session1 = client1.transport.create_processor._session + session2 = client2.transport.create_processor._session + assert session1 != session2 + session1 = client1.transport.delete_processor._session + session2 = client2.transport.delete_processor._session + assert session1 != session2 + session1 = client1.transport.enable_processor._session + session2 = client2.transport.enable_processor._session + assert session1 != session2 + session1 = client1.transport.disable_processor._session + session2 = client2.transport.disable_processor._session + assert session1 != session2 + session1 = client1.transport.set_default_processor_version._session + session2 = client2.transport.set_default_processor_version._session + assert session1 != session2 + session1 = client1.transport.review_document._session + session2 = client2.transport.review_document._session + assert session1 != session2 + session1 = client1.transport.evaluate_processor_version._session + session2 = client2.transport.evaluate_processor_version._session + assert session1 != session2 + session1 = client1.transport.get_evaluation._session + session2 = client2.transport.get_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_evaluations._session + session2 = client2.transport.list_evaluations._session + assert session1 != session2 +def test_document_processor_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentProcessorServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_document_processor_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) +def test_document_processor_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) +def test_document_processor_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_document_processor_service_grpc_lro_client(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_document_processor_service_grpc_lro_async_client(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +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, processor=processor, ) + actual = DocumentProcessorServiceClient.human_review_config_path(project, location, processor) + assert expected == actual + + +def test_parse_human_review_config_path(): + expected = { + "project": "clam", + "location": "whelk", + "processor": "octopus", + } + path = DocumentProcessorServiceClient.human_review_config_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_human_review_config_path(path) + assert expected == actual + +def test_processor_path(): + project = "oyster" + location = "nudibranch" + processor = "cuttlefish" + expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + actual = DocumentProcessorServiceClient.processor_path(project, location, processor) + assert expected == actual + + +def test_parse_processor_path(): + expected = { + "project": "mussel", + "location": "winkle", + "processor": "nautilus", + } + path = DocumentProcessorServiceClient.processor_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_processor_path(path) + assert expected == actual + +def test_processor_type_path(): + project = "scallop" + location = "abalone" + processor_type = "squid" + expected = "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) + actual = DocumentProcessorServiceClient.processor_type_path(project, location, processor_type) + assert expected == actual + + +def test_parse_processor_type_path(): + expected = { + "project": "clam", + "location": "whelk", + "processor_type": "octopus", + } + path = DocumentProcessorServiceClient.processor_type_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_processor_type_path(path) + assert expected == actual + +def test_processor_version_path(): + project = "oyster" + location = "nudibranch" + processor = "cuttlefish" + processor_version = "mussel" + expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) + actual = DocumentProcessorServiceClient.processor_version_path(project, location, processor, processor_version) + assert expected == actual + + +def test_parse_processor_version_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "processor": "scallop", + "processor_version": "abalone", + } + path = DocumentProcessorServiceClient.processor_version_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_processor_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentProcessorServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DocumentProcessorServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentProcessorServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DocumentProcessorServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentProcessorServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DocumentProcessorServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DocumentProcessorServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DocumentProcessorServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DocumentProcessorServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DocumentProcessorServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentProcessorServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_cancel_operation(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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(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 response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(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 response is the type that we expect. + assert response is None + +def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(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=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + 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.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + 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_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_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_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(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=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + 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_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_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_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(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 response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + 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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(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 response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(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=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + 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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(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 response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + 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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(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 response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(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=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(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=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + 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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1beta2/.coveragerc b/owl-bot-staging/v1beta2/.coveragerc new file mode 100644 index 00000000..46ab6093 --- /dev/null +++ b/owl-bot-staging/v1beta2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/documentai/__init__.py + google/cloud/documentai/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/v1beta2/.flake8 b/owl-bot-staging/v1beta2/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1beta2/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 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 +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1beta2/MANIFEST.in b/owl-bot-staging/v1beta2/MANIFEST.in new file mode 100644 index 00000000..cd0fd7a8 --- /dev/null +++ b/owl-bot-staging/v1beta2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/documentai *.py +recursive-include google/cloud/documentai_v1beta2 *.py diff --git a/owl-bot-staging/v1beta2/README.rst b/owl-bot-staging/v1beta2/README.rst new file mode 100644 index 00000000..484a3c1c --- /dev/null +++ b/owl-bot-staging/v1beta2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Documentai API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Documentai API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta2/docs/conf.py b/owl-bot-staging/v1beta2/docs/conf.py new file mode 100644 index 00000000..960a15f0 --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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. +# +# +# google-cloud-documentai documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-documentai" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-documentai-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-documentai.tex", + u"google-cloud-documentai Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-documentai", + u"Google Cloud Documentai Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-documentai", + u"google-cloud-documentai Documentation", + author, + "google-cloud-documentai", + "GAPIC library for Google Cloud Documentai API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst new file mode 100644 index 00000000..a0d0da7e --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst @@ -0,0 +1,6 @@ +DocumentUnderstandingService +---------------------------------------------- + +.. automodule:: google.cloud.documentai_v1beta2.services.document_understanding_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst new file mode 100644 index 00000000..13f4a238 --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Documentai v1beta2 API +================================================ +.. toctree:: + :maxdepth: 2 + + document_understanding_service diff --git a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst new file mode 100644 index 00000000..35540dd0 --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Documentai v1beta2 API +============================================= + +.. automodule:: google.cloud.documentai_v1beta2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta2/docs/index.rst b/owl-bot-staging/v1beta2/docs/index.rst new file mode 100644 index 00000000..38d5fbb5 --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + documentai_v1beta2/services + documentai_v1beta2/types diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py new file mode 100644 index 00000000..0fcf1b3b --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py @@ -0,0 +1,67 @@ +# -*- 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 google.cloud.documentai import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.documentai_v1beta2.services.document_understanding_service.client import DocumentUnderstandingServiceClient +from google.cloud.documentai_v1beta2.services.document_understanding_service.async_client import DocumentUnderstandingServiceAsyncClient + +from google.cloud.documentai_v1beta2.types.document import Document +from google.cloud.documentai_v1beta2.types.document_understanding import AutoMlParams +from google.cloud.documentai_v1beta2.types.document_understanding import BatchProcessDocumentsRequest +from google.cloud.documentai_v1beta2.types.document_understanding import BatchProcessDocumentsResponse +from google.cloud.documentai_v1beta2.types.document_understanding import EntityExtractionParams +from google.cloud.documentai_v1beta2.types.document_understanding import FormExtractionParams +from google.cloud.documentai_v1beta2.types.document_understanding import GcsDestination +from google.cloud.documentai_v1beta2.types.document_understanding import GcsSource +from google.cloud.documentai_v1beta2.types.document_understanding import InputConfig +from google.cloud.documentai_v1beta2.types.document_understanding import KeyValuePairHint +from google.cloud.documentai_v1beta2.types.document_understanding import OcrParams +from google.cloud.documentai_v1beta2.types.document_understanding import OperationMetadata +from google.cloud.documentai_v1beta2.types.document_understanding import OutputConfig +from google.cloud.documentai_v1beta2.types.document_understanding import ProcessDocumentRequest +from google.cloud.documentai_v1beta2.types.document_understanding import ProcessDocumentResponse +from google.cloud.documentai_v1beta2.types.document_understanding import TableBoundHint +from google.cloud.documentai_v1beta2.types.document_understanding import TableExtractionParams +from google.cloud.documentai_v1beta2.types.geometry import BoundingPoly +from google.cloud.documentai_v1beta2.types.geometry import NormalizedVertex +from google.cloud.documentai_v1beta2.types.geometry import Vertex + +__all__ = ('DocumentUnderstandingServiceClient', + 'DocumentUnderstandingServiceAsyncClient', + 'Document', + 'AutoMlParams', + 'BatchProcessDocumentsRequest', + 'BatchProcessDocumentsResponse', + 'EntityExtractionParams', + 'FormExtractionParams', + 'GcsDestination', + 'GcsSource', + 'InputConfig', + 'KeyValuePairHint', + 'OcrParams', + 'OperationMetadata', + 'OutputConfig', + 'ProcessDocumentRequest', + 'ProcessDocumentResponse', + 'TableBoundHint', + 'TableExtractionParams', + 'BoundingPoly', + 'NormalizedVertex', + 'Vertex', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py b/owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai/py.typed b/owl-bot-staging/v1beta2/google/cloud/documentai/py.typed new file mode 100644 index 00000000..81b45001 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py new file mode 100644 index 00000000..fc4e4dca --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py @@ -0,0 +1,68 @@ +# -*- 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 google.cloud.documentai_v1beta2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.document_understanding_service import DocumentUnderstandingServiceClient +from .services.document_understanding_service import DocumentUnderstandingServiceAsyncClient + +from .types.document import Document +from .types.document_understanding import AutoMlParams +from .types.document_understanding import BatchProcessDocumentsRequest +from .types.document_understanding import BatchProcessDocumentsResponse +from .types.document_understanding import EntityExtractionParams +from .types.document_understanding import FormExtractionParams +from .types.document_understanding import GcsDestination +from .types.document_understanding import GcsSource +from .types.document_understanding import InputConfig +from .types.document_understanding import KeyValuePairHint +from .types.document_understanding import OcrParams +from .types.document_understanding import OperationMetadata +from .types.document_understanding import OutputConfig +from .types.document_understanding import ProcessDocumentRequest +from .types.document_understanding import ProcessDocumentResponse +from .types.document_understanding import TableBoundHint +from .types.document_understanding import TableExtractionParams +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Vertex + +__all__ = ( + 'DocumentUnderstandingServiceAsyncClient', +'AutoMlParams', +'BatchProcessDocumentsRequest', +'BatchProcessDocumentsResponse', +'BoundingPoly', +'Document', +'DocumentUnderstandingServiceClient', +'EntityExtractionParams', +'FormExtractionParams', +'GcsDestination', +'GcsSource', +'InputConfig', +'KeyValuePairHint', +'NormalizedVertex', +'OcrParams', +'OperationMetadata', +'OutputConfig', +'ProcessDocumentRequest', +'ProcessDocumentResponse', +'TableBoundHint', +'TableExtractionParams', +'Vertex', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json new file mode 100644 index 00000000..633dcc19 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.documentai_v1beta2", + "protoPackage": "google.cloud.documentai.v1beta2", + "schema": "1.0", + "services": { + "DocumentUnderstandingService": { + "clients": { + "grpc": { + "libraryClient": "DocumentUnderstandingServiceClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentUnderstandingServiceAsyncClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed new file mode 100644 index 00000000..81b45001 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py new file mode 100644 index 00000000..7c124f17 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 .client import DocumentUnderstandingServiceClient +from .async_client import DocumentUnderstandingServiceAsyncClient + +__all__ = ( + 'DocumentUnderstandingServiceClient', + 'DocumentUnderstandingServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py new file mode 100644 index 00000000..8dbcefc1 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py @@ -0,0 +1,426 @@ +# -*- 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 collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.documentai_v1beta2 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.documentai_v1beta2.types import document +from google.cloud.documentai_v1beta2.types import document_understanding +from google.rpc import status_pb2 # type: ignore +from .transports.base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentUnderstandingServiceGrpcAsyncIOTransport +from .client import DocumentUnderstandingServiceClient + + +class DocumentUnderstandingServiceAsyncClient: + """Service to parse structured information from unstructured or + semi-structured documents using state-of-the-art Google AI such + as natural language, computer vision, and translation. + """ + + _client: DocumentUnderstandingServiceClient + + DEFAULT_ENDPOINT = DocumentUnderstandingServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DocumentUnderstandingServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(DocumentUnderstandingServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentUnderstandingServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentUnderstandingServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentUnderstandingServiceClient.common_project_path) + parse_common_project_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_project_path) + common_location_path = staticmethod(DocumentUnderstandingServiceClient.common_location_path) + parse_common_location_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentUnderstandingServiceAsyncClient: The constructed client. + """ + return DocumentUnderstandingServiceClient.from_service_account_info.__func__(DocumentUnderstandingServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentUnderstandingServiceAsyncClient: The constructed client. + """ + return DocumentUnderstandingServiceClient.from_service_account_file.__func__(DocumentUnderstandingServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DocumentUnderstandingServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DocumentUnderstandingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentUnderstandingServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentUnderstandingServiceClient).get_transport_class, type(DocumentUnderstandingServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentUnderstandingServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document understanding service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DocumentUnderstandingServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DocumentUnderstandingServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def batch_process_documents(self, + request: Optional[Union[document_understanding.BatchProcessDocumentsRequest, dict]] = None, + *, + requests: Optional[MutableSequence[document_understanding.ProcessDocumentRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + .. 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_v1beta2 + + async def sample_batch_process_documents(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() + + # Initialize request argument(s) + requests = documentai_v1beta2.ProcessDocumentRequest() + requests.input_config.gcs_source.uri = "uri_value" + requests.input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.BatchProcessDocumentsRequest( + requests=requests, + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest, dict]]): + The request object. Request to batch process documents + as an asynchronous operation. The output is written to + Cloud Storage as JSON in the [Document] format. + requests (:class:`MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]`): + Required. Individual requests for + each document. + + This corresponds to the ``requests`` 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_v1beta2.types.BatchProcessDocumentsResponse` Response to an batch document processing request. This is returned in + the LRO Operation after the operation is complete. + + """ + # 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([requests]) + 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_understanding.BatchProcessDocumentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if requests: + request.requests.extend(requests) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_process_documents, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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_understanding.BatchProcessDocumentsResponse, + metadata_type=document_understanding.OperationMetadata, + ) + + # Done; return the response. + return response + + async def process_document(self, + request: Optional[Union[document_understanding.ProcessDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Processes a single document. + + .. 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_v1beta2 + + async def sample_process_document(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() + + # Initialize request argument(s) + input_config = documentai_v1beta2.InputConfig() + input_config.gcs_source.uri = "uri_value" + input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.ProcessDocumentRequest( + input_config=input_config, + ) + + # Make the request + response = await client.process_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest, dict]]): + The request object. Request to process one document. + 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_v1beta2.types.Document: + Document represents the canonical + document resource in Document + Understanding AI. It is an interchange + format that provides insights into + documents and allows for collaboration + between users and Document Understanding + AI to iterate and optimize for quality. + + """ + # Create or coerce a protobuf request object. + request = document_understanding.ProcessDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.process_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentUnderstandingServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py new file mode 100644 index 00000000..086c8636 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py @@ -0,0 +1,606 @@ +# -*- 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 collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.documentai_v1beta2 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.documentai_v1beta2.types import document +from google.cloud.documentai_v1beta2.types import document_understanding +from google.rpc import status_pb2 # type: ignore +from .transports.base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentUnderstandingServiceGrpcTransport +from .transports.grpc_asyncio import DocumentUnderstandingServiceGrpcAsyncIOTransport + + +class DocumentUnderstandingServiceClientMeta(type): + """Metaclass for the DocumentUnderstandingService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentUnderstandingServiceTransport]] + _transport_registry["grpc"] = DocumentUnderstandingServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentUnderstandingServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DocumentUnderstandingServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DocumentUnderstandingServiceClient(metaclass=DocumentUnderstandingServiceClientMeta): + """Service to parse structured information from unstructured or + semi-structured documents using state-of-the-art Google AI such + as natural language, computer vision, and translation. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "documentai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentUnderstandingServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentUnderstandingServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DocumentUnderstandingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentUnderstandingServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DocumentUnderstandingServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document understanding service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, DocumentUnderstandingServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentUnderstandingServiceTransport): + # transport is a DocumentUnderstandingServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def batch_process_documents(self, + request: Optional[Union[document_understanding.BatchProcessDocumentsRequest, dict]] = None, + *, + requests: Optional[MutableSequence[document_understanding.ProcessDocumentRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + .. 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_v1beta2 + + def sample_batch_process_documents(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceClient() + + # Initialize request argument(s) + requests = documentai_v1beta2.ProcessDocumentRequest() + requests.input_config.gcs_source.uri = "uri_value" + requests.input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.BatchProcessDocumentsRequest( + requests=requests, + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest, dict]): + The request object. Request to batch process documents + as an asynchronous operation. The output is written to + Cloud Storage as JSON in the [Document] format. + requests (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]): + Required. Individual requests for + each document. + + This corresponds to the ``requests`` 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_v1beta2.types.BatchProcessDocumentsResponse` Response to an batch document processing request. This is returned in + the LRO Operation after the operation is complete. + + """ + # 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([requests]) + 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_understanding.BatchProcessDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_understanding.BatchProcessDocumentsRequest): + request = document_understanding.BatchProcessDocumentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_process_documents] + + # 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_understanding.BatchProcessDocumentsResponse, + metadata_type=document_understanding.OperationMetadata, + ) + + # Done; return the response. + return response + + def process_document(self, + request: Optional[Union[document_understanding.ProcessDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Processes a single document. + + .. 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_v1beta2 + + def sample_process_document(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceClient() + + # Initialize request argument(s) + input_config = documentai_v1beta2.InputConfig() + input_config.gcs_source.uri = "uri_value" + input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.ProcessDocumentRequest( + input_config=input_config, + ) + + # Make the request + response = client.process_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest, dict]): + The request object. Request to process one document. + 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_v1beta2.types.Document: + Document represents the canonical + document resource in Document + Understanding AI. It is an interchange + format that provides insights into + documents and allows for collaboration + between users and Document Understanding + AI to iterate and optimize for quality. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_understanding.ProcessDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_understanding.ProcessDocumentRequest): + request = document_understanding.ProcessDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.process_document] + + # 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, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DocumentUnderstandingServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentUnderstandingServiceClient", +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py new file mode 100644 index 00000000..4144c192 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- 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 collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentUnderstandingServiceTransport +from .grpc import DocumentUnderstandingServiceGrpcTransport +from .grpc_asyncio import DocumentUnderstandingServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentUnderstandingServiceTransport]] +_transport_registry['grpc'] = DocumentUnderstandingServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentUnderstandingServiceGrpcAsyncIOTransport + +__all__ = ( + 'DocumentUnderstandingServiceTransport', + 'DocumentUnderstandingServiceGrpcTransport', + 'DocumentUnderstandingServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py new file mode 100644 index 00000000..44c62488 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py @@ -0,0 +1,184 @@ +# -*- 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.documentai_v1beta2 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.documentai_v1beta2.types import document +from google.cloud.documentai_v1beta2.types import document_understanding +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DocumentUnderstandingServiceTransport(abc.ABC): + """Abstract transport class for DocumentUnderstandingService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'documentai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_process_documents: gapic_v1.method.wrap_method( + self.batch_process_documents, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.process_document: gapic_v1.method.wrap_method( + self.process_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_process_documents(self) -> Callable[ + [document_understanding.BatchProcessDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def process_document(self) -> Callable[ + [document_understanding.ProcessDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DocumentUnderstandingServiceTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py new file mode 100644 index 00000000..34e11453 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py @@ -0,0 +1,313 @@ +# -*- 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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.documentai_v1beta2.types import document +from google.cloud.documentai_v1beta2.types import document_understanding +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO + + +class DocumentUnderstandingServiceGrpcTransport(DocumentUnderstandingServiceTransport): + """gRPC backend transport for DocumentUnderstandingService. + + Service to parse structured information from unstructured or + semi-structured documents using state-of-the-art Google AI such + as natural language, computer vision, and translation. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def batch_process_documents(self) -> Callable[ + [document_understanding.BatchProcessDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch process documents method over gRPC. + + LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + Returns: + Callable[[~.BatchProcessDocumentsRequest], + ~.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 'batch_process_documents' not in self._stubs: + self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/BatchProcessDocuments', + request_serializer=document_understanding.BatchProcessDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_process_documents'] + + @property + def process_document(self) -> Callable[ + [document_understanding.ProcessDocumentRequest], + document.Document]: + r"""Return a callable for the process document method over gRPC. + + Processes a single document. + + Returns: + Callable[[~.ProcessDocumentRequest], + ~.Document]: + 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 'process_document' not in self._stubs: + self._stubs['process_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/ProcessDocument', + request_serializer=document_understanding.ProcessDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['process_document'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DocumentUnderstandingServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..f0b3c1ff --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py @@ -0,0 +1,312 @@ +# -*- 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. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.documentai_v1beta2.types import document +from google.cloud.documentai_v1beta2.types import document_understanding +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentUnderstandingServiceGrpcTransport + + +class DocumentUnderstandingServiceGrpcAsyncIOTransport(DocumentUnderstandingServiceTransport): + """gRPC AsyncIO backend transport for DocumentUnderstandingService. + + Service to parse structured information from unstructured or + semi-structured documents using state-of-the-art Google AI such + as natural language, computer vision, and translation. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def batch_process_documents(self) -> Callable[ + [document_understanding.BatchProcessDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch process documents method over gRPC. + + LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + Returns: + Callable[[~.BatchProcessDocumentsRequest], + 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 'batch_process_documents' not in self._stubs: + self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/BatchProcessDocuments', + request_serializer=document_understanding.BatchProcessDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_process_documents'] + + @property + def process_document(self) -> Callable[ + [document_understanding.ProcessDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the process document method over gRPC. + + Processes a single document. + + Returns: + Callable[[~.ProcessDocumentRequest], + Awaitable[~.Document]]: + 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 'process_document' not in self._stubs: + self._stubs['process_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/ProcessDocument', + request_serializer=document_understanding.ProcessDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['process_document'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DocumentUnderstandingServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py new file mode 100644 index 00000000..b038e3b0 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py @@ -0,0 +1,64 @@ +# -*- 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 .document import ( + Document, +) +from .document_understanding import ( + AutoMlParams, + BatchProcessDocumentsRequest, + BatchProcessDocumentsResponse, + EntityExtractionParams, + FormExtractionParams, + GcsDestination, + GcsSource, + InputConfig, + KeyValuePairHint, + OcrParams, + OperationMetadata, + OutputConfig, + ProcessDocumentRequest, + ProcessDocumentResponse, + TableBoundHint, + TableExtractionParams, +) +from .geometry import ( + BoundingPoly, + NormalizedVertex, + Vertex, +) + +__all__ = ( + 'Document', + 'AutoMlParams', + 'BatchProcessDocumentsRequest', + 'BatchProcessDocumentsResponse', + 'EntityExtractionParams', + 'FormExtractionParams', + 'GcsDestination', + 'GcsSource', + 'InputConfig', + 'KeyValuePairHint', + 'OcrParams', + 'OperationMetadata', + 'OutputConfig', + 'ProcessDocumentRequest', + 'ProcessDocumentResponse', + 'TableBoundHint', + 'TableExtractionParams', + 'BoundingPoly', + 'NormalizedVertex', + 'Vertex', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py new file mode 100644 index 00000000..01ca727d --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py @@ -0,0 +1,1080 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.documentai_v1beta2.types import geometry +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta2', + manifest={ + 'Document', + }, +) + + +class Document(proto.Message): + r"""Document represents the canonical document resource in + Document Understanding AI. + It is an interchange format that provides insights into + documents and allows for collaboration between users and + Document Understanding AI to iterate and optimize for quality. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Currently supports Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is not + supported. See `Google Cloud Storage Request + URIs `__ + for more info. + + This field is a member of `oneof`_ ``source``. + content (bytes): + Inline document content, represented as a stream of bytes. + Note: As with all ``bytes`` fields, protobuffers use a pure + binary representation, whereas JSON representations use + base64. + + This field is a member of `oneof`_ ``source``. + mime_type (str): + An IANA published MIME type (also referred to + as media type). For more information, see + https://www.iana.org/assignments/media-types/media-types.xhtml. + text (str): + UTF-8 encoded text in reading order from the + document. + text_styles (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Style]): + Styles for the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + pages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page]): + Visual page layout for the + [Document][google.cloud.documentai.v1beta2.Document]. + entities (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Entity]): + A list of entities detected on + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + For document shards, entities in this list may cross shard + boundaries. + entity_relations (MutableSequence[google.cloud.documentai_v1beta2.types.Document.EntityRelation]): + Relationship among + [Document.entities][google.cloud.documentai.v1beta2.Document.entities]. + shard_info (google.cloud.documentai_v1beta2.types.Document.ShardInfo): + Information about the sharding if this + document is sharded part of a larger document. + If the document is not sharded, this message is + not specified. + labels (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Label]): + [Label][google.cloud.documentai.v1beta2.Document.Label]s for + this document. + error (google.rpc.status_pb2.Status): + Any error that occurred while processing this + document. + """ + + class ShardInfo(proto.Message): + r"""For a large document, sharding may be performed to produce + several document shards. Each document shard contains this field + to detail which shard it is. + + Attributes: + shard_index (int): + The 0-based index of this shard. + shard_count (int): + Total number of shards. + text_offset (int): + The index of the first character in + [Document.text][google.cloud.documentai.v1beta2.Document.text] + in the overall document global text. + """ + + shard_index: int = proto.Field( + proto.INT64, + number=1, + ) + shard_count: int = proto.Field( + proto.INT64, + number=2, + ) + text_offset: int = proto.Field( + proto.INT64, + number=3, + ) + + class Label(proto.Message): + r"""Label attaches schema information and/or other metadata to segments + within a [Document][google.cloud.documentai.v1beta2.Document]. + Multiple [Label][google.cloud.documentai.v1beta2.Document.Label]s on + a single field can denote either different labels, different + instances of the same label created at different times, or some + combination of both. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + automl_model (str): + Label is generated AutoML model. This field stores the full + resource name of the AutoML model. + + Format: + ``projects/{project-id}/locations/{location-id}/models/{model-id}`` + + This field is a member of `oneof`_ ``source``. + name (str): + Name of the label. + When the label is generated from AutoML Text + Classification model, this field represents the + name of the category. + confidence (float): + Confidence score between 0 and 1 for label + assignment. + """ + + automl_model: str = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=3, + ) + + class Style(proto.Message): + r"""Annotation for common text style attributes. This adheres to + CSS conventions as much as possible. + + Attributes: + text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): + Text anchor indexing into the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + color (google.type.color_pb2.Color): + Text color. + background_color (google.type.color_pb2.Color): + Text background color. + font_weight (str): + Font weight. Possible values are normal, bold, bolder, and + lighter. https://www.w3schools.com/cssref/pr_font_weight.asp + text_style (str): + Text style. Possible values are normal, italic, and oblique. + https://www.w3schools.com/cssref/pr_font_font-style.asp + text_decoration (str): + Text decoration. Follows CSS standard. + https://www.w3schools.com/cssref/pr_text_text-decoration.asp + font_size (google.cloud.documentai_v1beta2.types.Document.Style.FontSize): + Font size. + """ + + class FontSize(proto.Message): + r"""Font size with unit. + + Attributes: + size (float): + Font size for the text. + unit (str): + Unit for the font size. Follows CSS naming + (in, px, pt, etc.). + """ + + size: float = proto.Field( + proto.FLOAT, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=2, + message=color_pb2.Color, + ) + background_color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=3, + message=color_pb2.Color, + ) + font_weight: str = proto.Field( + proto.STRING, + number=4, + ) + text_style: str = proto.Field( + proto.STRING, + number=5, + ) + text_decoration: str = proto.Field( + proto.STRING, + number=6, + ) + font_size: 'Document.Style.FontSize' = proto.Field( + proto.MESSAGE, + number=7, + message='Document.Style.FontSize', + ) + + class Page(proto.Message): + r"""A page in a [Document][google.cloud.documentai.v1beta2.Document]. + + Attributes: + page_number (int): + 1-based index for current + [Page][google.cloud.documentai.v1beta2.Document.Page] in a + parent [Document][google.cloud.documentai.v1beta2.Document]. + Useful when a page is taken out of a + [Document][google.cloud.documentai.v1beta2.Document] for + individual processing. + dimension (google.cloud.documentai_v1beta2.types.Document.Page.Dimension): + Physical dimension of the page. + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for the page. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + blocks (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Block]): + A list of visually detected text blocks on + the page. A block has a set of lines (collected + into paragraphs) that have a common line-spacing + and orientation. + paragraphs (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Paragraph]): + A list of visually detected text paragraphs + on the page. A collection of lines that a human + would perceive as a paragraph. + lines (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Line]): + A list of visually detected text lines on the + page. A collection of tokens that a human would + perceive as a line. + tokens (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Token]): + A list of visually detected tokens on the + page. + visual_elements (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.VisualElement]): + A list of detected non-text visual elements + e.g. checkbox, signature etc. on the page. + tables (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table]): + A list of visually detected tables on the + page. + form_fields (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.FormField]): + A list of visually detected form fields on + the page. + """ + + class Dimension(proto.Message): + r"""Dimension for the page. + + Attributes: + width (float): + Page width. + height (float): + Page height. + unit (str): + Dimension unit. + """ + + width: float = proto.Field( + proto.FLOAT, + number=1, + ) + height: float = proto.Field( + proto.FLOAT, + number=2, + ) + unit: str = proto.Field( + proto.STRING, + number=3, + ) + + class Layout(proto.Message): + r"""Visual element describing a layout unit on a page. + + Attributes: + text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): + Text anchor indexing into the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + confidence (float): + Confidence of the current + [Layout][google.cloud.documentai.v1beta2.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]. + bounding_poly (google.cloud.documentai_v1beta2.types.BoundingPoly): + The bounding polygon for the + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout]. + orientation (google.cloud.documentai_v1beta2.types.Document.Page.Layout.Orientation): + Detected orientation for the + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout]. + id (str): + Optional. This is the identifier used by referencing + [PageAnchor][google.cloud.documentai.v1beta2.Document.PageAnchor]s. + """ + class Orientation(proto.Enum): + r"""Detected human reading orientation. + + Values: + ORIENTATION_UNSPECIFIED (0): + Unspecified orientation. + PAGE_UP (1): + Orientation is aligned with page up. + PAGE_RIGHT (2): + Orientation is aligned with page right. + Turn the head 90 degrees clockwise from upright + to read. + PAGE_DOWN (3): + Orientation is aligned with page down. + Turn the head 180 degrees from upright to read. + PAGE_LEFT (4): + Orientation is aligned with page left. + Turn the head 90 degrees counterclockwise from + upright to read. + """ + ORIENTATION_UNSPECIFIED = 0 + PAGE_UP = 1 + PAGE_RIGHT = 2 + PAGE_DOWN = 3 + PAGE_LEFT = 4 + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + bounding_poly: geometry.BoundingPoly = proto.Field( + proto.MESSAGE, + number=3, + message=geometry.BoundingPoly, + ) + orientation: 'Document.Page.Layout.Orientation' = proto.Field( + proto.ENUM, + number=4, + enum='Document.Page.Layout.Orientation', + ) + id: str = proto.Field( + proto.STRING, + number=5, + ) + + class Block(proto.Message): + r"""A block has a set of lines (collected into paragraphs) that + have a common line-spacing and orientation. + + Attributes: + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for + [Block][google.cloud.documentai.v1beta2.Document.Page.Block]. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + + class Paragraph(proto.Message): + r"""A collection of lines that a human would perceive as a + paragraph. + + Attributes: + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for + [Paragraph][google.cloud.documentai.v1beta2.Document.Page.Paragraph]. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + + class Line(proto.Message): + r"""A collection of tokens that a human would perceive as a line. + Does not cross column boundaries, can be horizontal, vertical, + etc. + + Attributes: + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for + [Line][google.cloud.documentai.v1beta2.Document.Page.Line]. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + + class Token(proto.Message): + r"""A detected token. + + Attributes: + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for + [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. + detected_break (google.cloud.documentai_v1beta2.types.Document.Page.Token.DetectedBreak): + Detected break at the end of a + [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + class DetectedBreak(proto.Message): + r"""Detected break at the end of a + [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. + + Attributes: + type_ (google.cloud.documentai_v1beta2.types.Document.Page.Token.DetectedBreak.Type): + Detected break type. + """ + class Type(proto.Enum): + r"""Enum to denote the type of break found. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified break type. + SPACE (1): + A single whitespace. + WIDE_SPACE (2): + A wider whitespace. + HYPHEN (3): + A hyphen that indicates that a token has been + split across lines. + """ + TYPE_UNSPECIFIED = 0 + SPACE = 1 + WIDE_SPACE = 2 + HYPHEN = 3 + + type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( + proto.ENUM, + number=1, + enum='Document.Page.Token.DetectedBreak.Type', + ) + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Token.DetectedBreak', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + + class VisualElement(proto.Message): + r"""Detected non-text visual elements e.g. checkbox, signature + etc. on the page. + + Attributes: + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for + [VisualElement][google.cloud.documentai.v1beta2.Document.Page.VisualElement]. + type_ (str): + Type of the + [VisualElement][google.cloud.documentai.v1beta2.Document.Page.VisualElement]. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + + class Table(proto.Message): + r"""A table representation similar to HTML table structure. + + Attributes: + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for + [Table][google.cloud.documentai.v1beta2.Document.Page.Table]. + header_rows (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): + Header rows of the table. + body_rows (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): + Body rows of the table. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + class TableRow(proto.Message): + r"""A row of table cells. + + Attributes: + cells (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableCell]): + Cells that make up this row. + """ + + cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.Page.Table.TableCell', + ) + + class TableCell(proto.Message): + r"""A cell representation inside the table. + + Attributes: + layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for + [TableCell][google.cloud.documentai.v1beta2.Document.Page.Table.TableCell]. + row_span (int): + How many rows this cell spans. + col_span (int): + How many columns this cell spans. + detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + row_span: int = proto.Field( + proto.INT32, + number=2, + ) + col_span: int = proto.Field( + proto.INT32, + number=3, + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.Table.TableRow', + ) + body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.Table.TableRow', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + + class FormField(proto.Message): + r"""A form field detected on the page. + + Attributes: + field_name (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for the + [FormField][google.cloud.documentai.v1beta2.Document.Page.FormField] + name. e.g. ``Address``, ``Email``, ``Grand total``, + ``Phone number``, etc. + field_value (google.cloud.documentai_v1beta2.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] + for the + [FormField][google.cloud.documentai.v1beta2.Document.Page.FormField] + value. + name_detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages for name + together with confidence. + value_detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages for value + together with confidence. + value_type (str): + If the value is non-textual, this field represents the type. + Current valid values are: + + - blank (this indicates the field_value is normal text) + - "unfilled_checkbox" + - "filled_checkbox". + corrected_key_text (str): + An internal field, created for Labeling UI to + export key text. + corrected_value_text (str): + An internal field, created for Labeling UI to + export value text. + """ + + field_name: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + field_value: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Layout', + ) + name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + value_type: str = proto.Field( + proto.STRING, + number=5, + ) + corrected_key_text: str = proto.Field( + proto.STRING, + number=6, + ) + corrected_value_text: str = proto.Field( + proto.STRING, + number=7, + ) + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + confidence (float): + Confidence of detected language. Range [0, 1]. + """ + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + + page_number: int = proto.Field( + proto.INT32, + number=1, + ) + dimension: 'Document.Page.Dimension' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Dimension', + ) + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Document.Page.Block', + ) + paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Document.Page.Paragraph', + ) + lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Document.Page.Line', + ) + tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Document.Page.Token', + ) + visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Document.Page.VisualElement', + ) + tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Page.Table', + ) + form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='Document.Page.FormField', + ) + + class Entity(proto.Message): + r"""A phrase in the text that is a known entity type, such as a + person, an organization, or location. + + Attributes: + text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): + Provenance of the entity. Text anchor indexing into the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + type_ (str): + Required. Entity type from a schema e.g. ``Address``. + mention_text (str): + Text value in the document e.g. ``1600 Amphitheatre Pkwy``. + mention_id (str): + Deprecated. Use ``id`` field instead. + confidence (float): + Optional. Confidence of detected Schema entity. Range [0, + 1]. + page_anchor (google.cloud.documentai_v1beta2.types.Document.PageAnchor): + Optional. Represents the provenance of this + entity wrt. the location on the page where it + was found. + id (str): + Optional. Canonical id. This will be a unique + value in the entity list for this document. + """ + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + mention_text: str = proto.Field( + proto.STRING, + number=3, + ) + mention_id: str = proto.Field( + proto.STRING, + number=4, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=5, + ) + page_anchor: 'Document.PageAnchor' = proto.Field( + proto.MESSAGE, + number=6, + message='Document.PageAnchor', + ) + id: str = proto.Field( + proto.STRING, + number=7, + ) + + class EntityRelation(proto.Message): + r"""Relationship between + [Entities][google.cloud.documentai.v1beta2.Document.Entity]. + + Attributes: + subject_id (str): + Subject entity id. + object_id (str): + Object entity id. + relation (str): + Relationship description. + """ + + subject_id: str = proto.Field( + proto.STRING, + number=1, + ) + object_id: str = proto.Field( + proto.STRING, + number=2, + ) + relation: str = proto.Field( + proto.STRING, + number=3, + ) + + class TextAnchor(proto.Message): + r"""Text reference indexing into the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + + Attributes: + text_segments (MutableSequence[google.cloud.documentai_v1beta2.types.Document.TextAnchor.TextSegment]): + The text segments from the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + content (str): + Contains the content of the text span so that users do not + have to look it up in the text_segments. + """ + + class TextSegment(proto.Message): + r"""A text segment in the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. The + indices may be out of bounds which indicate that the text extends + into another document shard for large sharded documents. See + [ShardInfo.text_offset][google.cloud.documentai.v1beta2.Document.ShardInfo.text_offset] + + Attributes: + start_index (int): + [TextSegment][google.cloud.documentai.v1beta2.Document.TextAnchor.TextSegment] + start UTF-8 char index in the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + end_index (int): + [TextSegment][google.cloud.documentai.v1beta2.Document.TextAnchor.TextSegment] + half open end UTF-8 char index in the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + """ + + start_index: int = proto.Field( + proto.INT64, + number=1, + ) + end_index: int = proto.Field( + proto.INT64, + number=2, + ) + + text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.TextAnchor.TextSegment', + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + class PageAnchor(proto.Message): + r"""Referencing elements in + [Document.pages][google.cloud.documentai.v1beta2.Document.pages]. + + Attributes: + page_refs (MutableSequence[google.cloud.documentai_v1beta2.types.Document.PageAnchor.PageRef]): + One or more references to visual page + elements + """ + + class PageRef(proto.Message): + r"""Represents a weak reference to a page element within a + document. + + Attributes: + page (int): + Required. Index into the + [Document.pages][google.cloud.documentai.v1beta2.Document.pages] + element + layout_type (google.cloud.documentai_v1beta2.types.Document.PageAnchor.PageRef.LayoutType): + Optional. The type of the layout element that + is being referenced. If not specified the whole + page is assumed to be referenced. + layout_id (str): + Optional. The + [Page.Layout.id][google.cloud.documentai.v1beta2.Document.Page.Layout.id] + on the page that this element references. If + [LayoutRef.type][] is specified this id must also be + specified. + """ + class LayoutType(proto.Enum): + r"""The type of layout that is being referenced. + + Values: + LAYOUT_TYPE_UNSPECIFIED (0): + Layout Unspecified. + BLOCK (1): + References a + [Page.blocks][google.cloud.documentai.v1beta2.Document.Page.blocks] + element. + PARAGRAPH (2): + References a + [Page.paragraphs][google.cloud.documentai.v1beta2.Document.Page.paragraphs] + element. + LINE (3): + References a + [Page.lines][google.cloud.documentai.v1beta2.Document.Page.lines] + element. + TOKEN (4): + References a + [Page.tokens][google.cloud.documentai.v1beta2.Document.Page.tokens] + element. + VISUAL_ELEMENT (5): + References a + [Page.visual_elements][google.cloud.documentai.v1beta2.Document.Page.visual_elements] + element. + TABLE (6): + Refrrences a + [Page.tables][google.cloud.documentai.v1beta2.Document.Page.tables] + element. + FORM_FIELD (7): + References a + [Page.form_fields][google.cloud.documentai.v1beta2.Document.Page.form_fields] + element. + """ + LAYOUT_TYPE_UNSPECIFIED = 0 + BLOCK = 1 + PARAGRAPH = 2 + LINE = 3 + TOKEN = 4 + VISUAL_ELEMENT = 5 + TABLE = 6 + FORM_FIELD = 7 + + page: int = proto.Field( + proto.INT64, + number=1, + ) + layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( + proto.ENUM, + number=2, + enum='Document.PageAnchor.PageRef.LayoutType', + ) + layout_id: str = proto.Field( + proto.STRING, + number=3, + ) + + page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.PageAnchor.PageRef', + ) + + uri: str = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + content: bytes = proto.Field( + proto.BYTES, + number=2, + oneof='source', + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + text: str = proto.Field( + proto.STRING, + number=4, + ) + text_styles: MutableSequence[Style] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Style, + ) + pages: MutableSequence[Page] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Page, + ) + entities: MutableSequence[Entity] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Entity, + ) + entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=EntityRelation, + ) + shard_info: ShardInfo = proto.Field( + proto.MESSAGE, + number=9, + message=ShardInfo, + ) + labels: MutableSequence[Label] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=Label, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=10, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py new file mode 100644 index 00000000..ca3145bd --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py @@ -0,0 +1,591 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.documentai_v1beta2.types import geometry +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta2', + manifest={ + 'BatchProcessDocumentsRequest', + 'ProcessDocumentRequest', + 'BatchProcessDocumentsResponse', + 'ProcessDocumentResponse', + 'OcrParams', + 'TableExtractionParams', + 'TableBoundHint', + 'FormExtractionParams', + 'KeyValuePairHint', + 'EntityExtractionParams', + 'AutoMlParams', + 'InputConfig', + 'OutputConfig', + 'GcsSource', + 'GcsDestination', + 'OperationMetadata', + }, +) + + +class BatchProcessDocumentsRequest(proto.Message): + r"""Request to batch process documents as an asynchronous operation. The + output is written to Cloud Storage as JSON in the [Document] format. + + Attributes: + requests (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]): + Required. Individual requests for each + document. + parent (str): + Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no location is specified, a region will be chosen + automatically. + """ + + requests: MutableSequence['ProcessDocumentRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ProcessDocumentRequest', + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProcessDocumentRequest(proto.Message): + r"""Request to process one document. + + Attributes: + parent (str): + Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no location is specified, a region will be chosen + automatically. This field is only populated when used in + ProcessDocument method. + input_config (google.cloud.documentai_v1beta2.types.InputConfig): + Required. Information about the input file. + output_config (google.cloud.documentai_v1beta2.types.OutputConfig): + Optional. The desired output location. This + field is only needed in + BatchProcessDocumentsRequest. + document_type (str): + Specifies a known document type for deeper + structure detection. Valid values are currently + "general" and "invoice". If not provided, + "general"\ is used as default. If any other + value is given, the request is rejected. + table_extraction_params (google.cloud.documentai_v1beta2.types.TableExtractionParams): + Controls table extraction behavior. If not + specified, the system will decide reasonable + defaults. + form_extraction_params (google.cloud.documentai_v1beta2.types.FormExtractionParams): + Controls form extraction behavior. If not + specified, the system will decide reasonable + defaults. + entity_extraction_params (google.cloud.documentai_v1beta2.types.EntityExtractionParams): + Controls entity extraction behavior. If not + specified, the system will decide reasonable + defaults. + ocr_params (google.cloud.documentai_v1beta2.types.OcrParams): + Controls OCR behavior. If not specified, the + system will decide reasonable defaults. + automl_params (google.cloud.documentai_v1beta2.types.AutoMlParams): + Controls AutoML model prediction behavior. + AutoMlParams cannot be used together with other + Params. + """ + + parent: str = proto.Field( + proto.STRING, + number=9, + ) + input_config: 'InputConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='InputConfig', + ) + output_config: 'OutputConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='OutputConfig', + ) + document_type: str = proto.Field( + proto.STRING, + number=3, + ) + table_extraction_params: 'TableExtractionParams' = proto.Field( + proto.MESSAGE, + number=4, + message='TableExtractionParams', + ) + form_extraction_params: 'FormExtractionParams' = proto.Field( + proto.MESSAGE, + number=5, + message='FormExtractionParams', + ) + entity_extraction_params: 'EntityExtractionParams' = proto.Field( + proto.MESSAGE, + number=6, + message='EntityExtractionParams', + ) + ocr_params: 'OcrParams' = proto.Field( + proto.MESSAGE, + number=7, + message='OcrParams', + ) + automl_params: 'AutoMlParams' = proto.Field( + proto.MESSAGE, + number=8, + message='AutoMlParams', + ) + + +class BatchProcessDocumentsResponse(proto.Message): + r"""Response to an batch document processing request. This is + returned in the LRO Operation after the operation is complete. + + Attributes: + responses (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentResponse]): + Responses for each individual document. + """ + + responses: MutableSequence['ProcessDocumentResponse'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ProcessDocumentResponse', + ) + + +class ProcessDocumentResponse(proto.Message): + r"""Response to a single document processing request. + + Attributes: + input_config (google.cloud.documentai_v1beta2.types.InputConfig): + Information about the input file. This is the + same as the corresponding input config in the + request. + output_config (google.cloud.documentai_v1beta2.types.OutputConfig): + The output location of the parsed responses. The responses + are written to this location as JSON-serialized ``Document`` + objects. + """ + + input_config: 'InputConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='InputConfig', + ) + output_config: 'OutputConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='OutputConfig', + ) + + +class OcrParams(proto.Message): + r"""Parameters to control Optical Character Recognition (OCR) + behavior. + + Attributes: + language_hints (MutableSequence[str]): + List of languages to use for OCR. In most cases, an empty + value yields the best results since it enables automatic + language detection. For languages based on the Latin + alphabet, setting ``language_hints`` is not needed. In rare + cases, when the language of the text in the image is known, + setting a hint will help get better results (although it + will be a significant hindrance if the hint is wrong). + Document processing returns an error if one or more of the + specified languages is not one of the supported languages. + """ + + language_hints: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class TableExtractionParams(proto.Message): + r"""Parameters to control table extraction behavior. + + Attributes: + enabled (bool): + Whether to enable table extraction. + table_bound_hints (MutableSequence[google.cloud.documentai_v1beta2.types.TableBoundHint]): + Optional. Table bounding box hints that can + be provided to complex cases which our algorithm + cannot locate the table(s) in. + header_hints (MutableSequence[str]): + Optional. Table header hints. The extraction + will bias towards producing these terms as table + headers, which may improve accuracy. + model_version (str): + Model version of the table extraction system. + Default is "builtin/stable". Specify + "builtin/latest" for the latest model. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + table_bound_hints: MutableSequence['TableBoundHint'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TableBoundHint', + ) + header_hints: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + model_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class TableBoundHint(proto.Message): + r"""A hint for a table bounding box on the page for table + parsing. + + Attributes: + page_number (int): + Optional. Page number for multi-paged inputs + this hint applies to. If not provided, this hint + will apply to all pages by default. This value + is 1-based. + bounding_box (google.cloud.documentai_v1beta2.types.BoundingPoly): + Bounding box hint for a table on this page. The coordinates + must be normalized to [0,1] and the bounding box must be an + axis-aligned rectangle. + """ + + page_number: int = proto.Field( + proto.INT32, + number=1, + ) + bounding_box: geometry.BoundingPoly = proto.Field( + proto.MESSAGE, + number=2, + message=geometry.BoundingPoly, + ) + + +class FormExtractionParams(proto.Message): + r"""Parameters to control form extraction behavior. + + Attributes: + enabled (bool): + Whether to enable form extraction. + key_value_pair_hints (MutableSequence[google.cloud.documentai_v1beta2.types.KeyValuePairHint]): + User can provide pairs of (key text, value type) to improve + the parsing result. + + For example, if a document has a field called "Date" that + holds a date value and a field called "Amount" that may hold + either a currency value (e.g., "$500.00") or a simple number + value (e.g., "20"), you could use the following hints: [ + {"key": "Date", value_types: [ "DATE"]}, {"key": "Amount", + "value_types": [ "PRICE", "NUMBER" ]} ] + + If the value type is unknown, but you want to provide hints + for the keys, you can leave the value_types field blank. + e.g. {"key": "Date", "value_types": []} + model_version (str): + Model version of the form extraction system. Default is + "builtin/stable". Specify "builtin/latest" for the latest + model. For custom form models, specify: + “custom/{model_name}". Model name format is + "bucket_name/path/to/modeldir" corresponding to + "gs://bucket_name/path/to/modeldir" where annotated examples + are stored. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + key_value_pair_hints: MutableSequence['KeyValuePairHint'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='KeyValuePairHint', + ) + model_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +class KeyValuePairHint(proto.Message): + r"""User-provided hint for key value pair. + + Attributes: + key (str): + The key text for the hint. + value_types (MutableSequence[str]): + Type of the value. This is case-insensitive, and could be + one of: ADDRESS, LOCATION, ORGANIZATION, PERSON, + PHONE_NUMBER, ID, NUMBER, EMAIL, PRICE, TERMS, DATE, NAME. + Types not in this list will be ignored. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class EntityExtractionParams(proto.Message): + r"""Parameters to control entity extraction behavior. + + Attributes: + enabled (bool): + Whether to enable entity extraction. + model_version (str): + Model version of the entity extraction. + Default is "builtin/stable". Specify + "builtin/latest" for the latest model. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + model_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AutoMlParams(proto.Message): + r"""Parameters to control AutoML model prediction behavior. + + Attributes: + model (str): + Resource name of the AutoML model. + + Format: + ``projects/{project-id}/locations/{location-id}/models/{model-id}``. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InputConfig(proto.Message): + r"""The desired input location and metadata. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_source (google.cloud.documentai_v1beta2.types.GcsSource): + The Google Cloud Storage location to read the + input from. This must be a single file. + + This field is a member of `oneof`_ ``source``. + contents (bytes): + Content in bytes, represented as a stream of bytes. Note: As + with all ``bytes`` fields, proto buffer messages use a pure + binary representation, whereas JSON representations use + base64. + + This field only works for synchronous ProcessDocument + method. + + This field is a member of `oneof`_ ``source``. + mime_type (str): + Required. Mimetype of the input. Current supported mimetypes + are application/pdf, image/tiff, and image/gif. In addition, + application/json type is supported for requests with + [ProcessDocumentRequest.automl_params][google.cloud.documentai.v1beta2.ProcessDocumentRequest.automl_params] + field set. The JSON file needs to be in + [Document][google.cloud.documentai.v1beta2.Document] format. + """ + + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsSource', + ) + contents: bytes = proto.Field( + proto.BYTES, + number=3, + oneof='source', + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OutputConfig(proto.Message): + r"""The desired output location and metadata. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_destination (google.cloud.documentai_v1beta2.types.GcsDestination): + The Google Cloud Storage location to write + the output to. + + This field is a member of `oneof`_ ``destination``. + pages_per_shard (int): + The max number of pages to include into each output Document + shard JSON on Google Cloud Storage. + + The valid range is [1, 100]. If not specified, the default + value is 20. + + For example, for one pdf file with 100 pages, 100 parsed + pages will be produced. If ``pages_per_shard`` = 20, then 5 + Document shard JSON files each containing 20 parsed pages + will be written under the prefix + [OutputConfig.gcs_destination.uri][] and suffix + pages-x-to-y.json where x and y are 1-indexed page numbers. + + Example GCS outputs with 157 pages and pages_per_shard = 50: + + pages-001-to-050.json pages-051-to-100.json + pages-101-to-150.json pages-151-to-157.json + """ + + gcs_destination: 'GcsDestination' = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + pages_per_shard: int = proto.Field( + proto.INT32, + number=2, + ) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input file will + be read from. + + Attributes: + uri (str): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output file will + be written to. + + Attributes: + uri (str): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OperationMetadata(proto.Message): + r"""Contains metadata for the BatchProcessDocuments operation. + + Attributes: + state (google.cloud.documentai_v1beta2.types.OperationMetadata.State): + The state of the current batch processing. + state_message (str): + A message providing more details about the + current state of processing. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update time of the operation. + """ + class State(proto.Enum): + r""" + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + ACCEPTED (1): + Request is received. + WAITING (2): + Request operation is waiting for scheduling. + RUNNING (3): + Request is being processed. + SUCCEEDED (4): + The batch processing completed successfully. + CANCELLED (5): + The batch processing was cancelled. + FAILED (6): + The batch processing has failed. + """ + STATE_UNSPECIFIED = 0 + ACCEPTED = 1 + WAITING = 2 + RUNNING = 3 + SUCCEEDED = 4 + CANCELLED = 5 + FAILED = 6 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py new file mode 100644 index 00000000..343e7a5c --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py @@ -0,0 +1,97 @@ +# -*- 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 + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta2', + manifest={ + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + }, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate. + """ + + x: int = proto.Field( + proto.INT32, + number=1, + ) + y: int = proto.Field( + proto.INT32, + number=2, + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x: float = proto.Field( + proto.FLOAT, + number=1, + ) + y: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (MutableSequence[google.cloud.documentai_v1beta2.types.Vertex]): + The bounding polygon vertices. + normalized_vertices (MutableSequence[google.cloud.documentai_v1beta2.types.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices: MutableSequence['Vertex'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='NormalizedVertex', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/mypy.ini b/owl-bot-staging/v1beta2/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1beta2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1beta2/noxfile.py b/owl-bot-staging/v1beta2/noxfile.py new file mode 100644 index 00000000..8f7cea59 --- /dev/null +++ b/owl-bot-staging/v1beta2/noxfile.py @@ -0,0 +1,184 @@ +# -*- 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. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/documentai_v1beta2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py new file mode 100644 index 00000000..366d8b41 --- /dev/null +++ b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py @@ -0,0 +1,60 @@ +# -*- 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 BatchProcessDocuments +# 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_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_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_v1beta2 + + +async def sample_batch_process_documents(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() + + # Initialize request argument(s) + requests = documentai_v1beta2.ProcessDocumentRequest() + requests.input_config.gcs_source.uri = "uri_value" + requests.input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.BatchProcessDocumentsRequest( + requests=requests, + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_async] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py new file mode 100644 index 00000000..22cf5eea --- /dev/null +++ b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py @@ -0,0 +1,60 @@ +# -*- 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 BatchProcessDocuments +# 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_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_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_v1beta2 + + +def sample_batch_process_documents(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceClient() + + # Initialize request argument(s) + requests = documentai_v1beta2.ProcessDocumentRequest() + requests.input_config.gcs_source.uri = "uri_value" + requests.input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.BatchProcessDocumentsRequest( + requests=requests, + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_sync] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py new file mode 100644 index 00000000..586ed22a --- /dev/null +++ b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_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 ProcessDocument +# 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_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_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_v1beta2 + + +async def sample_process_document(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() + + # Initialize request argument(s) + input_config = documentai_v1beta2.InputConfig() + input_config.gcs_source.uri = "uri_value" + input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.ProcessDocumentRequest( + input_config=input_config, + ) + + # Make the request + response = await client.process_document(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_async] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py new file mode 100644 index 00000000..29460dd8 --- /dev/null +++ b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_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 ProcessDocument +# 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_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_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_v1beta2 + + +def sample_process_document(): + # Create a client + client = documentai_v1beta2.DocumentUnderstandingServiceClient() + + # Initialize request argument(s) + input_config = documentai_v1beta2.InputConfig() + input_config.gcs_source.uri = "uri_value" + input_config.mime_type = "mime_type_value" + + request = documentai_v1beta2.ProcessDocumentRequest( + input_config=input_config, + ) + + # Make the request + response = client.process_document(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_sync] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json b/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json new file mode 100644 index 00000000..ef56bd7e --- /dev/null +++ b/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json @@ -0,0 +1,329 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.documentai.v1beta2", + "version": "v1beta2" + } + ], + "language": "PYTHON", + "name": "google-cloud-documentai", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient", + "shortName": "DocumentUnderstandingServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient.batch_process_documents", + "method": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.BatchProcessDocuments", + "service": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", + "shortName": "DocumentUnderstandingService" + }, + "shortName": "BatchProcessDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]" + }, + { + "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": "batch_process_documents" + }, + "description": "Sample for BatchProcessDocuments", + "file": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient", + "shortName": "DocumentUnderstandingServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient.batch_process_documents", + "method": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.BatchProcessDocuments", + "service": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", + "shortName": "DocumentUnderstandingService" + }, + "shortName": "BatchProcessDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]" + }, + { + "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": "batch_process_documents" + }, + "description": "Sample for BatchProcessDocuments", + "file": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient", + "shortName": "DocumentUnderstandingServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient.process_document", + "method": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.ProcessDocument", + "service": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", + "shortName": "DocumentUnderstandingService" + }, + "shortName": "ProcessDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta2.types.ProcessDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1beta2.types.Document", + "shortName": "process_document" + }, + "description": "Sample for ProcessDocument", + "file": "documentai_v1beta2_generated_document_understanding_service_process_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta2_generated_document_understanding_service_process_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient", + "shortName": "DocumentUnderstandingServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient.process_document", + "method": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.ProcessDocument", + "service": { + "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", + "shortName": "DocumentUnderstandingService" + }, + "shortName": "ProcessDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta2.types.ProcessDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1beta2.types.Document", + "shortName": "process_document" + }, + "description": "Sample for ProcessDocument", + "file": "documentai_v1beta2_generated_document_understanding_service_process_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta2_generated_document_understanding_service_process_document_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py b/owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py new file mode 100644 index 00000000..bb31619b --- /dev/null +++ b/owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- 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. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class documentaiCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_process_documents': ('requests', 'parent', ), + 'process_document': ('input_config', 'parent', 'output_config', 'document_type', 'table_extraction_params', 'form_extraction_params', 'entity_extraction_params', 'ocr_params', 'automl_params', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=documentaiCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the documentai client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta2/setup.py b/owl-bot-staging/v1beta2/setup.py new file mode 100644 index 00000000..3b12ce4b --- /dev/null +++ b/owl-bot-staging/v1beta2/setup.py @@ -0,0 +1,90 @@ +# -*- 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. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-documentai' + + +description = "Google Cloud Documentai API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-documentai" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.10.txt b/owl-bot-staging/v1beta2/testing/constraints-3.10.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta2/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.11.txt b/owl-bot-staging/v1beta2/testing/constraints-3.11.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta2/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.12.txt b/owl-bot-staging/v1beta2/testing/constraints-3.12.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta2/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.7.txt b/owl-bot-staging/v1beta2/testing/constraints-3.7.txt new file mode 100644 index 00000000..6c44adfe --- /dev/null +++ b/owl-bot-staging/v1beta2/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.8.txt b/owl-bot-staging/v1beta2/testing/constraints-3.8.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta2/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.9.txt b/owl-bot-staging/v1beta2/testing/constraints-3.9.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta2/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta2/tests/__init__.py b/owl-bot-staging/v1beta2/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/__init__.py b/owl-bot-staging/v1beta2/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py b/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py new file mode 100644 index 00000000..2421aee9 --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py @@ -0,0 +1,1570 @@ +# -*- 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. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.documentai_v1beta2.services.document_understanding_service import DocumentUnderstandingServiceAsyncClient +from google.cloud.documentai_v1beta2.services.document_understanding_service import DocumentUnderstandingServiceClient +from google.cloud.documentai_v1beta2.services.document_understanding_service import transports +from google.cloud.documentai_v1beta2.types import document +from google.cloud.documentai_v1beta2.types import document_understanding +from google.cloud.documentai_v1beta2.types import geometry +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.rpc import status_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(None) is None + assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentUnderstandingServiceClient, "grpc"), + (DocumentUnderstandingServiceAsyncClient, "grpc_asyncio"), +]) +def test_document_understanding_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'documentai.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentUnderstandingServiceGrpcTransport, "grpc"), + (transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_document_understanding_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentUnderstandingServiceClient, "grpc"), + (DocumentUnderstandingServiceAsyncClient, "grpc_asyncio"), +]) +def test_document_understanding_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'documentai.googleapis.com:443' + ) + + +def test_document_understanding_service_client_get_transport_class(): + transport = DocumentUnderstandingServiceClient.get_transport_class() + available_transports = [ + transports.DocumentUnderstandingServiceGrpcTransport, + ] + assert transport in available_transports + + transport = DocumentUnderstandingServiceClient.get_transport_class("grpc") + assert transport == transports.DocumentUnderstandingServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc"), + (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DocumentUnderstandingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceClient)) +@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceAsyncClient)) +def test_document_understanding_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DocumentUnderstandingServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DocumentUnderstandingServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", "true"), + (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", "false"), + (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DocumentUnderstandingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceClient)) +@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_document_understanding_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DocumentUnderstandingServiceClient, DocumentUnderstandingServiceAsyncClient +]) +@mock.patch.object(DocumentUnderstandingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceClient)) +@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceAsyncClient)) +def test_document_understanding_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc"), + (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_document_understanding_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_document_understanding_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_document_understanding_service_client_client_options_from_dict(): + with mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentUnderstandingServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_document_understanding_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "documentai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="documentai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + document_understanding.BatchProcessDocumentsRequest, + dict, +]) +def test_batch_process_documents(request_type, transport: str = 'grpc'): + client = DocumentUnderstandingServiceClient( + 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.batch_process_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_process_documents(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_understanding.BatchProcessDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_process_documents_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 = DocumentUnderstandingServiceClient( + 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.batch_process_documents), + '__call__') as call: + client.batch_process_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_understanding.BatchProcessDocumentsRequest() + +@pytest.mark.asyncio +async def test_batch_process_documents_async(transport: str = 'grpc_asyncio', request_type=document_understanding.BatchProcessDocumentsRequest): + client = DocumentUnderstandingServiceAsyncClient( + 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.batch_process_documents), + '__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.batch_process_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_understanding.BatchProcessDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_process_documents_async_from_dict(): + await test_batch_process_documents_async(request_type=dict) + + +def test_batch_process_documents_field_headers(): + client = DocumentUnderstandingServiceClient( + 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_understanding.BatchProcessDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_process_documents(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_batch_process_documents_field_headers_async(): + client = DocumentUnderstandingServiceAsyncClient( + 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_understanding.BatchProcessDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_process_documents(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_batch_process_documents_flattened(): + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__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.batch_process_documents( + requests=[document_understanding.ProcessDocumentRequest(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].requests + mock_val = [document_understanding.ProcessDocumentRequest(parent='parent_value')] + assert arg == mock_val + + +def test_batch_process_documents_flattened_error(): + client = DocumentUnderstandingServiceClient( + 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.batch_process_documents( + document_understanding.BatchProcessDocumentsRequest(), + requests=[document_understanding.ProcessDocumentRequest(parent='parent_value')], + ) + +@pytest.mark.asyncio +async def test_batch_process_documents_flattened_async(): + client = DocumentUnderstandingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__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.batch_process_documents( + requests=[document_understanding.ProcessDocumentRequest(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].requests + mock_val = [document_understanding.ProcessDocumentRequest(parent='parent_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_process_documents_flattened_error_async(): + client = DocumentUnderstandingServiceAsyncClient( + 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.batch_process_documents( + document_understanding.BatchProcessDocumentsRequest(), + requests=[document_understanding.ProcessDocumentRequest(parent='parent_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + document_understanding.ProcessDocumentRequest, + dict, +]) +def test_process_document(request_type, transport: str = 'grpc'): + client = DocumentUnderstandingServiceClient( + 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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + mime_type='mime_type_value', + text='text_value', + uri='uri_value', + ) + response = client.process_document(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_understanding.ProcessDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.mime_type == 'mime_type_value' + assert response.text == 'text_value' + + +def test_process_document_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 = DocumentUnderstandingServiceClient( + 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.process_document), + '__call__') as call: + client.process_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_understanding.ProcessDocumentRequest() + +@pytest.mark.asyncio +async def test_process_document_async(transport: str = 'grpc_asyncio', request_type=document_understanding.ProcessDocumentRequest): + client = DocumentUnderstandingServiceAsyncClient( + 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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + mime_type='mime_type_value', + text='text_value', + )) + response = await client.process_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_understanding.ProcessDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.mime_type == 'mime_type_value' + assert response.text == 'text_value' + + +@pytest.mark.asyncio +async def test_process_document_async_from_dict(): + await test_process_document_async(request_type=dict) + + +def test_process_document_field_headers(): + client = DocumentUnderstandingServiceClient( + 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_understanding.ProcessDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.process_document), + '__call__') as call: + call.return_value = document.Document() + client.process_document(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_process_document_field_headers_async(): + client = DocumentUnderstandingServiceAsyncClient( + 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_understanding.ProcessDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.process_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.process_document(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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DocumentUnderstandingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DocumentUnderstandingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentUnderstandingServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DocumentUnderstandingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentUnderstandingServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentUnderstandingServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentUnderstandingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentUnderstandingServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentUnderstandingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentUnderstandingServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentUnderstandingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentUnderstandingServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentUnderstandingServiceGrpcTransport, + transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", +]) +def test_transport_kind(transport_name): + transport = DocumentUnderstandingServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentUnderstandingServiceGrpcTransport, + ) + +def test_document_understanding_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentUnderstandingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_document_understanding_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentUnderstandingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'batch_process_documents', + 'process_document', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_document_understanding_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentUnderstandingServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_document_understanding_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentUnderstandingServiceTransport() + adc.assert_called_once() + + +def test_document_understanding_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentUnderstandingServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentUnderstandingServiceGrpcTransport, + transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, + ], +) +def test_document_understanding_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentUnderstandingServiceGrpcTransport, + transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, + ], +) +def test_document_understanding_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentUnderstandingServiceGrpcTransport, grpc_helpers), + (transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_document_understanding_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "documentai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="documentai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentUnderstandingServiceGrpcTransport, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport]) +def test_document_understanding_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_document_understanding_service_host_no_port(transport_name): + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'documentai.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_document_understanding_service_host_with_port(transport_name): + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'documentai.googleapis.com:8000' + ) + +def test_document_understanding_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentUnderstandingServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_document_understanding_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentUnderstandingServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentUnderstandingServiceGrpcTransport, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport]) +def test_document_understanding_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentUnderstandingServiceGrpcTransport, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport]) +def test_document_understanding_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_document_understanding_service_grpc_lro_client(): + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_document_understanding_service_grpc_lro_async_client(): + client = DocumentUnderstandingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentUnderstandingServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DocumentUnderstandingServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentUnderstandingServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentUnderstandingServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DocumentUnderstandingServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentUnderstandingServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentUnderstandingServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DocumentUnderstandingServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentUnderstandingServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DocumentUnderstandingServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DocumentUnderstandingServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentUnderstandingServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DocumentUnderstandingServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DocumentUnderstandingServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentUnderstandingServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.DocumentUnderstandingServiceTransport, '_prep_wrapped_messages') as prep: + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentUnderstandingServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentUnderstandingServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentUnderstandingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = DocumentUnderstandingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport), + (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1beta3/.coveragerc b/owl-bot-staging/v1beta3/.coveragerc new file mode 100644 index 00000000..46ab6093 --- /dev/null +++ b/owl-bot-staging/v1beta3/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/documentai/__init__.py + google/cloud/documentai/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/v1beta3/.flake8 b/owl-bot-staging/v1beta3/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1beta3/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 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 +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1beta3/MANIFEST.in b/owl-bot-staging/v1beta3/MANIFEST.in new file mode 100644 index 00000000..af799d71 --- /dev/null +++ b/owl-bot-staging/v1beta3/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/documentai *.py +recursive-include google/cloud/documentai_v1beta3 *.py diff --git a/owl-bot-staging/v1beta3/README.rst b/owl-bot-staging/v1beta3/README.rst new file mode 100644 index 00000000..484a3c1c --- /dev/null +++ b/owl-bot-staging/v1beta3/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Documentai API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Documentai API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta3/docs/conf.py b/owl-bot-staging/v1beta3/docs/conf.py new file mode 100644 index 00000000..960a15f0 --- /dev/null +++ b/owl-bot-staging/v1beta3/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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. +# +# +# google-cloud-documentai documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-documentai" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-documentai-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-documentai.tex", + u"google-cloud-documentai Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-documentai", + u"Google Cloud Documentai Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-documentai", + u"google-cloud-documentai Documentation", + author, + "google-cloud-documentai", + "GAPIC library for Google Cloud Documentai API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst new file mode 100644 index 00000000..4d8d5f9e --- /dev/null +++ b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst @@ -0,0 +1,10 @@ +DocumentProcessorService +------------------------------------------ + +.. automodule:: google.cloud.documentai_v1beta3.services.document_processor_service + :members: + :inherited-members: + +.. automodule:: google.cloud.documentai_v1beta3.services.document_processor_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst new file mode 100644 index 00000000..d19a944b --- /dev/null +++ b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Documentai v1beta3 API +================================================ +.. toctree:: + :maxdepth: 2 + + document_processor_service diff --git a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst new file mode 100644 index 00000000..31b489da --- /dev/null +++ b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Documentai v1beta3 API +============================================= + +.. automodule:: google.cloud.documentai_v1beta3.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta3/docs/index.rst b/owl-bot-staging/v1beta3/docs/index.rst new file mode 100644 index 00000000..f4d3a84d --- /dev/null +++ b/owl-bot-staging/v1beta3/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + documentai_v1beta3/services + documentai_v1beta3/types diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py new file mode 100644 index 00000000..5da30913 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py @@ -0,0 +1,165 @@ +# -*- 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 google.cloud.documentai import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.documentai_v1beta3.services.document_processor_service.client import DocumentProcessorServiceClient +from google.cloud.documentai_v1beta3.services.document_processor_service.async_client import DocumentProcessorServiceAsyncClient + +from google.cloud.documentai_v1beta3.types.barcode import Barcode +from google.cloud.documentai_v1beta3.types.document import Document +from google.cloud.documentai_v1beta3.types.document_io import BatchDocumentsInputConfig +from google.cloud.documentai_v1beta3.types.document_io import DocumentOutputConfig +from google.cloud.documentai_v1beta3.types.document_io import GcsDocument +from google.cloud.documentai_v1beta3.types.document_io import GcsDocuments +from google.cloud.documentai_v1beta3.types.document_io import GcsPrefix +from google.cloud.documentai_v1beta3.types.document_io import OcrConfig +from google.cloud.documentai_v1beta3.types.document_io import RawDocument +from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import CreateProcessorRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorVersionMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorVersionRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import FetchProcessorTypesRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import FetchProcessorTypesResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import GetEvaluationRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorTypeRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorVersionRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import HumanReviewStatus +from google.cloud.documentai_v1beta3.types.document_processor_service import ListEvaluationsRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import ListEvaluationsResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorsRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorsResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorTypesRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorTypesResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorVersionsRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorVersionsResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessOptions +from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentOperationMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionMetadata +from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionResponse +from google.cloud.documentai_v1beta3.types.document_schema import DocumentSchema +from google.cloud.documentai_v1beta3.types.evaluation import Evaluation +from google.cloud.documentai_v1beta3.types.evaluation import EvaluationReference +from google.cloud.documentai_v1beta3.types.geometry import BoundingPoly +from google.cloud.documentai_v1beta3.types.geometry import NormalizedVertex +from google.cloud.documentai_v1beta3.types.geometry import Vertex +from google.cloud.documentai_v1beta3.types.operation_metadata import CommonOperationMetadata +from google.cloud.documentai_v1beta3.types.processor import Processor +from google.cloud.documentai_v1beta3.types.processor import ProcessorVersion +from google.cloud.documentai_v1beta3.types.processor_type import ProcessorType + +__all__ = ('DocumentProcessorServiceClient', + 'DocumentProcessorServiceAsyncClient', + 'Barcode', + 'Document', + 'BatchDocumentsInputConfig', + 'DocumentOutputConfig', + 'GcsDocument', + 'GcsDocuments', + 'GcsPrefix', + 'OcrConfig', + 'RawDocument', + 'BatchProcessMetadata', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'CreateProcessorRequest', + 'DeleteProcessorMetadata', + 'DeleteProcessorRequest', + 'DeleteProcessorVersionMetadata', + 'DeleteProcessorVersionRequest', + 'DeployProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DisableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'EnableProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EvaluateProcessorVersionMetadata', + 'EvaluateProcessorVersionRequest', + 'EvaluateProcessorVersionResponse', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetEvaluationRequest', + 'GetProcessorRequest', + 'GetProcessorTypeRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListEvaluationsRequest', + 'ListEvaluationsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessOptions', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'TrainProcessorVersionMetadata', + 'TrainProcessorVersionRequest', + 'TrainProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + 'Evaluation', + 'EvaluationReference', + 'BoundingPoly', + 'NormalizedVertex', + 'Vertex', + 'CommonOperationMetadata', + 'Processor', + 'ProcessorVersion', + 'ProcessorType', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py b/owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai/py.typed b/owl-bot-staging/v1beta3/google/cloud/documentai/py.typed new file mode 100644 index 00000000..81b45001 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py new file mode 100644 index 00000000..63a3fb42 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py @@ -0,0 +1,166 @@ +# -*- 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 google.cloud.documentai_v1beta3 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.document_processor_service import DocumentProcessorServiceClient +from .services.document_processor_service import DocumentProcessorServiceAsyncClient + +from .types.barcode import Barcode +from .types.document import Document +from .types.document_io import BatchDocumentsInputConfig +from .types.document_io import DocumentOutputConfig +from .types.document_io import GcsDocument +from .types.document_io import GcsDocuments +from .types.document_io import GcsPrefix +from .types.document_io import OcrConfig +from .types.document_io import RawDocument +from .types.document_processor_service import BatchProcessMetadata +from .types.document_processor_service import BatchProcessRequest +from .types.document_processor_service import BatchProcessResponse +from .types.document_processor_service import CreateProcessorRequest +from .types.document_processor_service import DeleteProcessorMetadata +from .types.document_processor_service import DeleteProcessorRequest +from .types.document_processor_service import DeleteProcessorVersionMetadata +from .types.document_processor_service import DeleteProcessorVersionRequest +from .types.document_processor_service import DeployProcessorVersionMetadata +from .types.document_processor_service import DeployProcessorVersionRequest +from .types.document_processor_service import DeployProcessorVersionResponse +from .types.document_processor_service import DisableProcessorMetadata +from .types.document_processor_service import DisableProcessorRequest +from .types.document_processor_service import DisableProcessorResponse +from .types.document_processor_service import EnableProcessorMetadata +from .types.document_processor_service import EnableProcessorRequest +from .types.document_processor_service import EnableProcessorResponse +from .types.document_processor_service import EvaluateProcessorVersionMetadata +from .types.document_processor_service import EvaluateProcessorVersionRequest +from .types.document_processor_service import EvaluateProcessorVersionResponse +from .types.document_processor_service import FetchProcessorTypesRequest +from .types.document_processor_service import FetchProcessorTypesResponse +from .types.document_processor_service import GetEvaluationRequest +from .types.document_processor_service import GetProcessorRequest +from .types.document_processor_service import GetProcessorTypeRequest +from .types.document_processor_service import GetProcessorVersionRequest +from .types.document_processor_service import HumanReviewStatus +from .types.document_processor_service import ListEvaluationsRequest +from .types.document_processor_service import ListEvaluationsResponse +from .types.document_processor_service import ListProcessorsRequest +from .types.document_processor_service import ListProcessorsResponse +from .types.document_processor_service import ListProcessorTypesRequest +from .types.document_processor_service import ListProcessorTypesResponse +from .types.document_processor_service import ListProcessorVersionsRequest +from .types.document_processor_service import ListProcessorVersionsResponse +from .types.document_processor_service import ProcessOptions +from .types.document_processor_service import ProcessRequest +from .types.document_processor_service import ProcessResponse +from .types.document_processor_service import ReviewDocumentOperationMetadata +from .types.document_processor_service import ReviewDocumentRequest +from .types.document_processor_service import ReviewDocumentResponse +from .types.document_processor_service import SetDefaultProcessorVersionMetadata +from .types.document_processor_service import SetDefaultProcessorVersionRequest +from .types.document_processor_service import SetDefaultProcessorVersionResponse +from .types.document_processor_service import TrainProcessorVersionMetadata +from .types.document_processor_service import TrainProcessorVersionRequest +from .types.document_processor_service import TrainProcessorVersionResponse +from .types.document_processor_service import UndeployProcessorVersionMetadata +from .types.document_processor_service import UndeployProcessorVersionRequest +from .types.document_processor_service import UndeployProcessorVersionResponse +from .types.document_schema import DocumentSchema +from .types.evaluation import Evaluation +from .types.evaluation import EvaluationReference +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Vertex +from .types.operation_metadata import CommonOperationMetadata +from .types.processor import Processor +from .types.processor import ProcessorVersion +from .types.processor_type import ProcessorType + +__all__ = ( + 'DocumentProcessorServiceAsyncClient', +'Barcode', +'BatchDocumentsInputConfig', +'BatchProcessMetadata', +'BatchProcessRequest', +'BatchProcessResponse', +'BoundingPoly', +'CommonOperationMetadata', +'CreateProcessorRequest', +'DeleteProcessorMetadata', +'DeleteProcessorRequest', +'DeleteProcessorVersionMetadata', +'DeleteProcessorVersionRequest', +'DeployProcessorVersionMetadata', +'DeployProcessorVersionRequest', +'DeployProcessorVersionResponse', +'DisableProcessorMetadata', +'DisableProcessorRequest', +'DisableProcessorResponse', +'Document', +'DocumentOutputConfig', +'DocumentProcessorServiceClient', +'DocumentSchema', +'EnableProcessorMetadata', +'EnableProcessorRequest', +'EnableProcessorResponse', +'EvaluateProcessorVersionMetadata', +'EvaluateProcessorVersionRequest', +'EvaluateProcessorVersionResponse', +'Evaluation', +'EvaluationReference', +'FetchProcessorTypesRequest', +'FetchProcessorTypesResponse', +'GcsDocument', +'GcsDocuments', +'GcsPrefix', +'GetEvaluationRequest', +'GetProcessorRequest', +'GetProcessorTypeRequest', +'GetProcessorVersionRequest', +'HumanReviewStatus', +'ListEvaluationsRequest', +'ListEvaluationsResponse', +'ListProcessorTypesRequest', +'ListProcessorTypesResponse', +'ListProcessorVersionsRequest', +'ListProcessorVersionsResponse', +'ListProcessorsRequest', +'ListProcessorsResponse', +'NormalizedVertex', +'OcrConfig', +'ProcessOptions', +'ProcessRequest', +'ProcessResponse', +'Processor', +'ProcessorType', +'ProcessorVersion', +'RawDocument', +'ReviewDocumentOperationMetadata', +'ReviewDocumentRequest', +'ReviewDocumentResponse', +'SetDefaultProcessorVersionMetadata', +'SetDefaultProcessorVersionRequest', +'SetDefaultProcessorVersionResponse', +'TrainProcessorVersionMetadata', +'TrainProcessorVersionRequest', +'TrainProcessorVersionResponse', +'UndeployProcessorVersionMetadata', +'UndeployProcessorVersionRequest', +'UndeployProcessorVersionResponse', +'Vertex', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json new file mode 100644 index 00000000..95c46773 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json @@ -0,0 +1,358 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.documentai_v1beta3", + "protoPackage": "google.cloud.documentai.v1beta3", + "schema": "1.0", + "services": { + "DocumentProcessorService": { + "clients": { + "grpc": { + "libraryClient": "DocumentProcessorServiceClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeleteProcessorVersion": { + "methods": [ + "delete_processor_version" + ] + }, + "DeployProcessorVersion": { + "methods": [ + "deploy_processor_version" + ] + }, + "DisableProcessor": { + "methods": [ + "disable_processor" + ] + }, + "EnableProcessor": { + "methods": [ + "enable_processor" + ] + }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorType": { + "methods": [ + "get_processor_type" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListProcessorTypes": { + "methods": [ + "list_processor_types" + ] + }, + "ListProcessorVersions": { + "methods": [ + "list_processor_versions" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + }, + "ReviewDocument": { + "methods": [ + "review_document" + ] + }, + "SetDefaultProcessorVersion": { + "methods": [ + "set_default_processor_version" + ] + }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentProcessorServiceAsyncClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeleteProcessorVersion": { + "methods": [ + "delete_processor_version" + ] + }, + "DeployProcessorVersion": { + "methods": [ + "deploy_processor_version" + ] + }, + "DisableProcessor": { + "methods": [ + "disable_processor" + ] + }, + "EnableProcessor": { + "methods": [ + "enable_processor" + ] + }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorType": { + "methods": [ + "get_processor_type" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListProcessorTypes": { + "methods": [ + "list_processor_types" + ] + }, + "ListProcessorVersions": { + "methods": [ + "list_processor_versions" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + }, + "ReviewDocument": { + "methods": [ + "review_document" + ] + }, + "SetDefaultProcessorVersion": { + "methods": [ + "set_default_processor_version" + ] + }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_version" + ] + } + } + }, + "rest": { + "libraryClient": "DocumentProcessorServiceClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "batch_process_documents" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeleteProcessorVersion": { + "methods": [ + "delete_processor_version" + ] + }, + "DeployProcessorVersion": { + "methods": [ + "deploy_processor_version" + ] + }, + "DisableProcessor": { + "methods": [ + "disable_processor" + ] + }, + "EnableProcessor": { + "methods": [ + "enable_processor" + ] + }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorType": { + "methods": [ + "get_processor_type" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListProcessorTypes": { + "methods": [ + "list_processor_types" + ] + }, + "ListProcessorVersions": { + "methods": [ + "list_processor_versions" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "ProcessDocument": { + "methods": [ + "process_document" + ] + }, + "ReviewDocument": { + "methods": [ + "review_document" + ] + }, + "SetDefaultProcessorVersion": { + "methods": [ + "set_default_processor_version" + ] + }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed new file mode 100644 index 00000000..81b45001 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py new file mode 100644 index 00000000..0e16e431 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 .client import DocumentProcessorServiceClient +from .async_client import DocumentProcessorServiceAsyncClient + +__all__ = ( + 'DocumentProcessorServiceClient', + 'DocumentProcessorServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py new file mode 100644 index 00000000..b70bd29c --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py @@ -0,0 +1,2981 @@ +# -*- 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 collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.documentai_v1beta3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.documentai_v1beta3.services.document_processor_service import pagers +from google.cloud.documentai_v1beta3.types import document +from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import document_schema +from google.cloud.documentai_v1beta3.types import 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 +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport +from .client import DocumentProcessorServiceClient + + +class DocumentProcessorServiceAsyncClient: + """Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + """ + + _client: DocumentProcessorServiceClient + + 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) + parse_human_review_config_path = staticmethod(DocumentProcessorServiceClient.parse_human_review_config_path) + processor_path = staticmethod(DocumentProcessorServiceClient.processor_path) + parse_processor_path = staticmethod(DocumentProcessorServiceClient.parse_processor_path) + processor_type_path = staticmethod(DocumentProcessorServiceClient.processor_type_path) + parse_processor_type_path = staticmethod(DocumentProcessorServiceClient.parse_processor_type_path) + processor_version_path = staticmethod(DocumentProcessorServiceClient.processor_version_path) + parse_processor_version_path = staticmethod(DocumentProcessorServiceClient.parse_processor_version_path) + common_billing_account_path = staticmethod(DocumentProcessorServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentProcessorServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentProcessorServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentProcessorServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentProcessorServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentProcessorServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentProcessorServiceClient.common_project_path) + parse_common_project_path = staticmethod(DocumentProcessorServiceClient.parse_common_project_path) + common_location_path = staticmethod(DocumentProcessorServiceClient.common_location_path) + parse_common_location_path = staticmethod(DocumentProcessorServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceAsyncClient: The constructed client. + """ + return DocumentProcessorServiceClient.from_service_account_info.__func__(DocumentProcessorServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceAsyncClient: The constructed client. + """ + return DocumentProcessorServiceClient.from_service_account_file.__func__(DocumentProcessorServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DocumentProcessorServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DocumentProcessorServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentProcessorServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentProcessorServiceClient).get_transport_class, type(DocumentProcessorServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document processor service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DocumentProcessorServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DocumentProcessorServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def process_document(self, + request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.ProcessResponse: + r"""Processes a single document. + + .. 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_process_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = await client.process_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.ProcessRequest, dict]]): + The request object. Request message for the process + document method. + name (:class:`str`): + Required. The resource name of the + [Processor][google.cloud.documentai.v1beta3.Processor] + or + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to use for processing. If a + [Processor][google.cloud.documentai.v1beta3.Processor] + is specified, the server will use its [default + version][google.cloud.documentai.v1beta3.Processor.default_processor_version]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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.ProcessResponse: + Response message for the process + document 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([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.ProcessRequest(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.process_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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 batch_process_documents(self, + request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + .. 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_batch_process_documents(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(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.BatchProcessRequest, dict]]): + The request object. Request message for batch process + document method. + name (:class:`str`): + Required. The resource name of + [Processor][google.cloud.documentai.v1beta3.Processor] + or + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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.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.BatchProcessResponse` + Response message for batch process document 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([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.BatchProcessRequest(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.batch_process_documents, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.BatchProcessResponse, + metadata_type=document_processor_service.BatchProcessMetadata, + ) + + # Done; return the response. + return response + + async def fetch_processor_types(self, + request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.FetchProcessorTypesResponse: + r"""Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + .. 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_fetch_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.fetch_processor_types(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest, dict]]): + The request object. Request message for fetch processor + types. + parent (:class:`str`): + Required. The project of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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.types.FetchProcessorTypesResponse: + Response message for fetch processor + types. + + """ + # 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.FetchProcessorTypesRequest(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.fetch_processor_types, + 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, + ) + + # Done; return the response. + return response + + async def list_processor_types(self, + request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorTypesAsyncPager: + r"""Lists the processor types that exist. + + .. 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_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest, dict]]): + The request object. Request message for list processor + types. + parent (:class:`str`): + Required. The location of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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.ListProcessorTypesAsyncPager: + Response message for list processor + types. + 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.ListProcessorTypesRequest(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_processor_types, + 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.ListProcessorTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_processor_type(self, + request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor_type.ProcessorType: + r"""Gets a processor type detail. + + .. 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_processor_type(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_type(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest, dict]]): + The request object. Request message for get processor. + name (:class:`str`): + Required. The processor type resource + name. + + 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.ProcessorType: + A processor type is responsible for + performing a certain document + understanding task on a certain type of + document. + + """ + # 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.GetProcessorTypeRequest(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_processor_type, + 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_processors(self, + request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsAsyncPager: + r"""Lists all processors which belong to this project. + + .. 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_processors(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorsRequest, dict]]): + The request object. Request message for list all + processors belongs to a project. + parent (:class:`str`): + Required. The parent (project and location) which owns + this collection of Processors. Format: + ``projects/{project}/locations/{location}`` + + 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.ListProcessorsAsyncPager: + Response message for list processors. + 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.ListProcessorsRequest(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_processors, + 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.ListProcessorsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_processor(self, + request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.Processor: + r"""Gets a processor detail. + + .. 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_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorRequest, dict]]): + The request object. Request message for get processor. + name (:class:`str`): + Required. The processor resource + name. + + 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.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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.GetProcessorRequest(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_processor, + 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 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.ProcessorVersion: + r"""Gets a processor version detail. + + .. 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_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest, dict]]): + The request object. Request message for get processor + version. + name (:class:`str`): + Required. The processor resource + name. + + 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.ProcessorVersion: + A processor version is an + implementation of a processor. Each + processor can have multiple versions, + pre-trained by Google internally or + up-trained by the customer. At a time, a + processor can only have one default + version version. So the processor's + behavior (when processing documents) is + defined by a default version + + """ + # 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.GetProcessorVersionRequest(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_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(( + ("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_processor_versions(self, + request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorVersionsAsyncPager: + r"""Lists all versions of a processor. + + .. 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_processor_versions(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest, dict]]): + The request object. Request message for list all + processor versions belongs to a processor. + parent (:class:`str`): + Required. The parent (project, location and processor) + to list all versions. 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. + 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.ListProcessorVersionsAsyncPager: + Response message for list processors. + 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.ListProcessorVersionsRequest(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_processor_versions, + 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.ListProcessorVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_processor_version(self, + request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the processor version, all artifacts under + the processor version will be deleted. + + .. 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_delete_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_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.DeleteProcessorVersionRequest, dict]]): + The request object. Request message for the delete + processor version method. + name (:class:`str`): + Required. The processor version + resource name to be deleted. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorVersionRequest(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.delete_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(( + ("name", request.name), + )), + ) + + # 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, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def deploy_processor_version(self, + request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys the 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_deploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_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.DeployProcessorVersionRequest, dict]]): + The request object. Request message for the deploy + processor version method. + name (:class:`str`): + Required. The processor version + resource name to be deployed. + + 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.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.DeployProcessorVersionResponse` + Response message for the deploy processor version + 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([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.DeployProcessorVersionRequest(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.deploy_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(( + ("name", request.name), + )), + ) + + # 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.DeployProcessorVersionResponse, + metadata_type=document_processor_service.DeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def undeploy_processor_version(self, + request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Undeploys the 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_undeploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_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.UndeployProcessorVersionRequest, dict]]): + The request object. Request message for the undeploy + processor version method. + name (:class:`str`): + Required. The processor version + resource name to be undeployed. + + 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.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.UndeployProcessorVersionResponse` + Response message for the undeploy processor version + 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([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.UndeployProcessorVersionRequest(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.undeploy_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(( + ("name", request.name), + )), + ) + + # 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.UndeployProcessorVersionResponse, + metadata_type=document_processor_service.UndeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def create_processor(self, + request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[gcd_processor.Processor] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_processor.Processor: + r"""Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + .. 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_create_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.CreateProcessorRequest, dict]]): + The request object. Request message for create a + processor. Notice this request is sent to a regionalized + backend service, and if the processor type is not + available on that region, the creation will fail. + parent (:class:`str`): + Required. The parent (project and location) under which + to create the processor. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (:class:`google.cloud.documentai_v1beta3.types.Processor`): + Required. The processor to be created, requires + [processor_type] and [display_name] to be set. Also, the + processor is under CMEK if CMEK fields are set. + + This corresponds to the ``processor`` 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.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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]) + 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.CreateProcessorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_processor, + 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, + ) + + # Done; return the response. + return response + + async def delete_processor(self, + request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + .. 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_delete_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(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.DeleteProcessorRequest, dict]]): + The request object. Request message for the delete + processor method. + name (:class:`str`): + Required. The processor resource name + to be deleted. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorRequest(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.delete_processor, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorMetadata, + ) + + # Done; return the response. + return response + + async def enable_processor(self, + request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Enables a processor + + .. 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_enable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(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.EnableProcessorRequest, dict]]): + The request object. Request message for the enable + processor method. + 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.EnableProcessorResponse` Response message for the enable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + request = document_processor_service.EnableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.enable_processor, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.EnableProcessorResponse, + metadata_type=document_processor_service.EnableProcessorMetadata, + ) + + # Done; return the response. + return response + + async def disable_processor(self, + request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Disables a processor + + .. 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_disable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(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.DisableProcessorRequest, dict]]): + The request object. Request message for the disable + processor method. + 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.DisableProcessorResponse` Response message for the disable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + request = document_processor_service.DisableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.disable_processor, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.DisableProcessorResponse, + metadata_type=document_processor_service.DisableProcessorMetadata, + ) + + # Done; return the response. + return response + + async def set_default_processor_version(self, + request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Set the default (active) version of a + [Processor][google.cloud.documentai.v1beta3.Processor] that will + be used in + [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. + + .. 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_set_default_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_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.SetDefaultProcessorVersionRequest, dict]]): + The request object. Request message for the set default + processor version method. + 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.SetDefaultProcessorVersionResponse` + Response message for set default processor version + method. + + """ + # Create or coerce a protobuf request object. + request = document_processor_service.SetDefaultProcessorVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_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", request.processor), + )), + ) + + # 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.SetDefaultProcessorVersionResponse, + metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def review_document(self, + request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, + *, + human_review_config: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Send a document for Human Review. The input document + should be processed by the specified processor. + + .. 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_review_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(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.ReviewDocumentRequest, dict]]): + The request object. Request message for review document + method. + human_review_config (:class:`str`): + Required. The resource name of the + HumanReviewConfig that the document will + be reviewed with. + + This corresponds to the ``human_review_config`` 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.ReviewDocumentResponse` + Response message for review document 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([human_review_config]) + 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.ReviewDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if human_review_config is not None: + request.human_review_config = human_review_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.review_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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(( + ("human_review_config", request.human_review_config), + )), + ) + + # 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.ReviewDocumentResponse, + metadata_type=document_processor_service.ReviewDocumentOperationMetadata, + ) + + # 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + 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: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + 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 cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + 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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + 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 __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentProcessorServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py new file mode 100644 index 00000000..c0fbf101 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py @@ -0,0 +1,3198 @@ +# -*- 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 collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.documentai_v1beta3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.documentai_v1beta3.services.document_processor_service import pagers +from google.cloud.documentai_v1beta3.types import document +from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import document_schema +from google.cloud.documentai_v1beta3.types import 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 +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentProcessorServiceGrpcTransport +from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport +from .transports.rest import DocumentProcessorServiceRestTransport + + +class DocumentProcessorServiceClientMeta(type): + """Metaclass for the DocumentProcessorService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] + _transport_registry["grpc"] = DocumentProcessorServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentProcessorServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DocumentProcessorServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DocumentProcessorServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DocumentProcessorServiceClient(metaclass=DocumentProcessorServiceClientMeta): + """Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "documentai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentProcessorServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DocumentProcessorServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentProcessorServiceTransport: The transport used by the client + instance. + """ + 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,location: str,processor: str,) -> str: + """Returns a fully-qualified human_review_config string.""" + return "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) + + @staticmethod + def parse_human_review_config_path(path: str) -> Dict[str,str]: + """Parses a human_review_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/humanReviewConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_path(project: str,location: str,processor: str,) -> str: + """Returns a fully-qualified processor string.""" + return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + + @staticmethod + def parse_processor_path(path: str) -> Dict[str,str]: + """Parses a processor path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_type_path(project: str,location: str,processor_type: str,) -> str: + """Returns a fully-qualified processor_type string.""" + return "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) + + @staticmethod + def parse_processor_type_path(path: str) -> Dict[str,str]: + """Parses a processor_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processorTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_version_path(project: str,location: str,processor: str,processor_version: str,) -> str: + """Returns a fully-qualified processor_version string.""" + return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) + + @staticmethod + def parse_processor_version_path(path: str) -> Dict[str,str]: + """Parses a processor_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DocumentProcessorServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document processor service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, DocumentProcessorServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentProcessorServiceTransport): + # transport is a DocumentProcessorServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def process_document(self, + request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.ProcessResponse: + r"""Processes a single document. + + .. 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_process_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = client.process_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.ProcessRequest, dict]): + The request object. Request message for the process + document method. + name (str): + Required. The resource name of the + [Processor][google.cloud.documentai.v1beta3.Processor] + or + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to use for processing. If a + [Processor][google.cloud.documentai.v1beta3.Processor] + is specified, the server will use its [default + version][google.cloud.documentai.v1beta3.Processor.default_processor_version]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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.ProcessResponse: + Response message for the process + document 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([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.ProcessRequest. + # 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.ProcessRequest): + request = document_processor_service.ProcessRequest(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.process_document] + + # 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 batch_process_documents(self, + request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + .. 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_batch_process_documents(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.BatchProcessRequest, dict]): + The request object. Request message for batch process + document method. + name (str): + Required. The resource name of + [Processor][google.cloud.documentai.v1beta3.Processor] + or + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + 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.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.BatchProcessResponse` + Response message for batch process document 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([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.BatchProcessRequest. + # 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.BatchProcessRequest): + request = document_processor_service.BatchProcessRequest(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.batch_process_documents] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.BatchProcessResponse, + metadata_type=document_processor_service.BatchProcessMetadata, + ) + + # Done; return the response. + return response + + def fetch_processor_types(self, + request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.FetchProcessorTypesResponse: + r"""Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + .. 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_fetch_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = client.fetch_processor_types(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest, dict]): + The request object. Request message for fetch processor + types. + parent (str): + Required. The project of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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.types.FetchProcessorTypesResponse: + Response message for fetch processor + types. + + """ + # 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.FetchProcessorTypesRequest. + # 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.FetchProcessorTypesRequest): + request = document_processor_service.FetchProcessorTypesRequest(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.fetch_processor_types] + + # 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, + ) + + # Done; return the response. + return response + + def list_processor_types(self, + request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorTypesPager: + r"""Lists the processor types that exist. + + .. 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_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest, dict]): + The request object. Request message for list processor + types. + parent (str): + Required. The location of processor type to list. The + available processor types may depend on the + allow-listing on projects. Format: + ``projects/{project}/locations/{location}`` + + 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.ListProcessorTypesPager: + Response message for list processor + types. + 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.ListProcessorTypesRequest. + # 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.ListProcessorTypesRequest): + request = document_processor_service.ListProcessorTypesRequest(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_processor_types] + + # 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.ListProcessorTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_processor_type(self, + request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor_type.ProcessorType: + r"""Gets a processor type detail. + + .. 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_processor_type(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_type(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest, dict]): + The request object. Request message for get processor. + name (str): + Required. The processor type resource + name. + + 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.ProcessorType: + A processor type is responsible for + performing a certain document + understanding task on a certain type of + document. + + """ + # 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.GetProcessorTypeRequest. + # 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.GetProcessorTypeRequest): + request = document_processor_service.GetProcessorTypeRequest(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_processor_type] + + # 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_processors(self, + request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsPager: + r"""Lists all processors which belong to this project. + + .. 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_processors(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.ListProcessorsRequest, dict]): + The request object. Request message for list all + processors belongs to a project. + parent (str): + Required. The parent (project and location) which owns + this collection of Processors. Format: + ``projects/{project}/locations/{location}`` + + 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.ListProcessorsPager: + Response message for list processors. + 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.ListProcessorsRequest. + # 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.ListProcessorsRequest): + request = document_processor_service.ListProcessorsRequest(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_processors] + + # 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.ListProcessorsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_processor(self, + request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.Processor: + r"""Gets a processor detail. + + .. 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_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.GetProcessorRequest, dict]): + The request object. Request message for get processor. + name (str): + Required. The processor resource + name. + + 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.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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.GetProcessorRequest. + # 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.GetProcessorRequest): + request = document_processor_service.GetProcessorRequest(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_processor] + + # 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 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> processor.ProcessorVersion: + r"""Gets a processor version detail. + + .. 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_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest, dict]): + The request object. Request message for get processor + version. + name (str): + Required. The processor resource + name. + + 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.ProcessorVersion: + A processor version is an + implementation of a processor. Each + processor can have multiple versions, + pre-trained by Google internally or + up-trained by the customer. At a time, a + processor can only have one default + version version. So the processor's + behavior (when processing documents) is + defined by a default version + + """ + # 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.GetProcessorVersionRequest. + # 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.GetProcessorVersionRequest): + request = document_processor_service.GetProcessorVersionRequest(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_processor_version] + + # 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_processor_versions(self, + request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorVersionsPager: + r"""Lists all versions of a processor. + + .. 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_processor_versions(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest, dict]): + The request object. Request message for list all + processor versions belongs to a processor. + parent (str): + Required. The parent (project, location and processor) + to list all versions. 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. + 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.ListProcessorVersionsPager: + Response message for list processors. + 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.ListProcessorVersionsRequest. + # 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.ListProcessorVersionsRequest): + request = document_processor_service.ListProcessorVersionsRequest(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_processor_versions] + + # 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.ListProcessorVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_processor_version(self, + request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the processor version, all artifacts under + the processor version will be deleted. + + .. 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_delete_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_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.DeleteProcessorVersionRequest, dict]): + The request object. Request message for the delete + processor version method. + name (str): + Required. The processor version + resource name to be deleted. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorVersionRequest. + # 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.DeleteProcessorVersionRequest): + request = document_processor_service.DeleteProcessorVersionRequest(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.delete_processor_version] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def deploy_processor_version(self, + request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deploys the 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_deploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_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.DeployProcessorVersionRequest, dict]): + The request object. Request message for the deploy + processor version method. + name (str): + Required. The processor version + resource name to be deployed. + + 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.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.DeployProcessorVersionResponse` + Response message for the deploy processor version + 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([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.DeployProcessorVersionRequest. + # 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.DeployProcessorVersionRequest): + request = document_processor_service.DeployProcessorVersionRequest(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.deploy_processor_version] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.DeployProcessorVersionResponse, + metadata_type=document_processor_service.DeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def undeploy_processor_version(self, + request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Undeploys the 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_undeploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_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.UndeployProcessorVersionRequest, dict]): + The request object. Request message for the undeploy + processor version method. + name (str): + Required. The processor version + resource name to be undeployed. + + 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.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.UndeployProcessorVersionResponse` + Response message for the undeploy processor version + 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([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.UndeployProcessorVersionRequest. + # 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.UndeployProcessorVersionRequest): + request = document_processor_service.UndeployProcessorVersionRequest(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.undeploy_processor_version] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.UndeployProcessorVersionResponse, + metadata_type=document_processor_service.UndeployProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def create_processor(self, + request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[gcd_processor.Processor] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_processor.Processor: + r"""Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + .. 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_create_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.CreateProcessorRequest, dict]): + The request object. Request message for create a + processor. Notice this request is sent to a regionalized + backend service, and if the processor type is not + available on that region, the creation will fail. + parent (str): + Required. The parent (project and location) under which + to create the processor. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (google.cloud.documentai_v1beta3.types.Processor): + Required. The processor to be created, requires + [processor_type] and [display_name] to be set. Also, the + processor is under CMEK if CMEK fields are set. + + This corresponds to the ``processor`` 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.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + # 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]) + 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.CreateProcessorRequest. + # 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.CreateProcessorRequest): + request = document_processor_service.CreateProcessorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_processor] + + # 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, + ) + + # Done; return the response. + return response + + def delete_processor(self, + request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + .. 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_delete_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.DeleteProcessorRequest, dict]): + The request object. Request message for the delete + processor method. + name (str): + Required. The processor resource name + to be deleted. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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.DeleteProcessorRequest. + # 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.DeleteProcessorRequest): + request = document_processor_service.DeleteProcessorRequest(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.delete_processor] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=document_processor_service.DeleteProcessorMetadata, + ) + + # Done; return the response. + return response + + def enable_processor(self, + request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Enables a processor + + .. 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_enable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.EnableProcessorRequest, dict]): + The request object. Request message for the enable + processor method. + 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.EnableProcessorResponse` Response message for the enable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.EnableProcessorRequest. + # 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.EnableProcessorRequest): + request = document_processor_service.EnableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.enable_processor] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.EnableProcessorResponse, + metadata_type=document_processor_service.EnableProcessorMetadata, + ) + + # Done; return the response. + return response + + def disable_processor(self, + request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Disables a processor + + .. 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_disable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.DisableProcessorRequest, dict]): + The request object. Request message for the disable + processor method. + 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.DisableProcessorResponse` Response message for the disable processor method. + Intentionally empty proto for adding fields in + future. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.DisableProcessorRequest. + # 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.DisableProcessorRequest): + request = document_processor_service.DisableProcessorRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.disable_processor] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.DisableProcessorResponse, + metadata_type=document_processor_service.DisableProcessorMetadata, + ) + + # Done; return the response. + return response + + def set_default_processor_version(self, + request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Set the default (active) version of a + [Processor][google.cloud.documentai.v1beta3.Processor] that will + be used in + [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. + + .. 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_set_default_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_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.SetDefaultProcessorVersionRequest, dict]): + The request object. Request message for the set default + processor version method. + 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.SetDefaultProcessorVersionResponse` + Response message for set default processor version + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.SetDefaultProcessorVersionRequest. + # 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.SetDefaultProcessorVersionRequest): + request = document_processor_service.SetDefaultProcessorVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_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", request.processor), + )), + ) + + # 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.SetDefaultProcessorVersionResponse, + metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def review_document(self, + request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, + *, + human_review_config: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Send a document for Human Review. The input document + should be processed by the specified processor. + + .. 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_review_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.ReviewDocumentRequest, dict]): + The request object. Request message for review document + method. + human_review_config (str): + Required. The resource name of the + HumanReviewConfig that the document will + be reviewed with. + + This corresponds to the ``human_review_config`` 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.ReviewDocumentResponse` + Response message for review document 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([human_review_config]) + 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.ReviewDocumentRequest. + # 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.ReviewDocumentRequest): + request = document_processor_service.ReviewDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if human_review_config is not None: + request.human_review_config = human_review_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.review_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("human_review_config", request.human_review_config), + )), + ) + + # 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.ReviewDocumentResponse, + metadata_type=document_processor_service.ReviewDocumentOperationMetadata, + ) + + # 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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: Union[float, object] = gapic_v1.method.DEFAULT, + 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) -> "DocumentProcessorServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + 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: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + 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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentProcessorServiceClient", +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py new file mode 100644 index 00000000..a7d62c87 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py @@ -0,0 +1,505 @@ +# -*- 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 Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import evaluation +from google.cloud.documentai_v1beta3.types import processor +from google.cloud.documentai_v1beta3.types import processor_type + + +class ListProcessorTypesPager: + """A pager for iterating through ``list_processor_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processor_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessorTypes`` requests and continue to iterate + through the ``processor_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` + 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.ListProcessorTypesResponse], + request: document_processor_service.ListProcessorTypesRequest, + response: document_processor_service.ListProcessorTypesResponse, + *, + 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.ListProcessorTypesRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse): + 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: + 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[processor_type.ProcessorType]: + for page in self.pages: + yield from page.processor_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorTypesAsyncPager: + """A pager for iterating through ``list_processor_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processor_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessorTypes`` requests and continue to iterate + through the ``processor_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` + 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.ListProcessorTypesResponse]], + request: document_processor_service.ListProcessorTypesRequest, + response: document_processor_service.ListProcessorTypesResponse, + *, + 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.ListProcessorTypesRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse): + 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: + 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[processor_type.ProcessorType]: + async def async_generator(): + async for page in self.pages: + for response in page.processor_types: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` + 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.ListProcessorsResponse], + request: document_processor_service.ListProcessorsRequest, + response: document_processor_service.ListProcessorsResponse, + *, + 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.ListProcessorsRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListProcessorsResponse): + 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.ListProcessorsRequest(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.ListProcessorsResponse]: + 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[processor.Processor]: + for page in self.pages: + yield from page.processors + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsAsyncPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` + 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.ListProcessorsResponse]], + request: document_processor_service.ListProcessorsRequest, + response: document_processor_service.ListProcessorsResponse, + *, + 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.ListProcessorsRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListProcessorsResponse): + 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.ListProcessorsRequest(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.ListProcessorsResponse]: + 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[processor.Processor]: + async def async_generator(): + async for page in self.pages: + for response in page.processors: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorVersionsPager: + """A pager for iterating through ``list_processor_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processor_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessorVersions`` requests and continue to iterate + through the ``processor_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` + 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.ListProcessorVersionsResponse], + request: document_processor_service.ListProcessorVersionsRequest, + response: document_processor_service.ListProcessorVersionsResponse, + *, + 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.ListProcessorVersionsRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse): + 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: + 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[processor.ProcessorVersion]: + for page in self.pages: + yield from page.processor_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorVersionsAsyncPager: + """A pager for iterating through ``list_processor_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processor_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessorVersions`` requests and continue to iterate + through the ``processor_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` + 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.ListProcessorVersionsResponse]], + request: document_processor_service.ListProcessorVersionsRequest, + response: document_processor_service.ListProcessorVersionsResponse, + *, + 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.ListProcessorVersionsRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse): + 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: + 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[processor.ProcessorVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.processor_versions: + yield response + + return 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/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py new file mode 100644 index 00000000..cb5f6e80 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- 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 collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentProcessorServiceTransport +from .grpc import DocumentProcessorServiceGrpcTransport +from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport +from .rest import DocumentProcessorServiceRestTransport +from .rest import DocumentProcessorServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] +_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DocumentProcessorServiceRestTransport + +__all__ = ( + 'DocumentProcessorServiceTransport', + 'DocumentProcessorServiceGrpcTransport', + 'DocumentProcessorServiceGrpcAsyncIOTransport', + 'DocumentProcessorServiceRestTransport', + 'DocumentProcessorServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py new file mode 100644 index 00000000..a403440c --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py @@ -0,0 +1,519 @@ +# -*- 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.documentai_v1beta3 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import 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 +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DocumentProcessorServiceTransport(abc.ABC): + """Abstract transport class for DocumentProcessorService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'documentai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.process_document: gapic_v1.method.wrap_method( + self.process_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.batch_process_documents: gapic_v1.method.wrap_method( + self.batch_process_documents, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.fetch_processor_types: gapic_v1.method.wrap_method( + self.fetch_processor_types, + default_timeout=None, + client_info=client_info, + ), + self.list_processor_types: gapic_v1.method.wrap_method( + self.list_processor_types, + default_timeout=None, + client_info=client_info, + ), + self.get_processor_type: gapic_v1.method.wrap_method( + self.get_processor_type, + default_timeout=None, + client_info=client_info, + ), + self.list_processors: gapic_v1.method.wrap_method( + self.list_processors, + default_timeout=None, + client_info=client_info, + ), + self.get_processor: gapic_v1.method.wrap_method( + self.get_processor, + 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, + client_info=client_info, + ), + self.list_processor_versions: gapic_v1.method.wrap_method( + self.list_processor_versions, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor_version: gapic_v1.method.wrap_method( + self.delete_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.deploy_processor_version: gapic_v1.method.wrap_method( + self.deploy_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_processor_version: gapic_v1.method.wrap_method( + self.undeploy_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.create_processor: gapic_v1.method.wrap_method( + self.create_processor, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor: gapic_v1.method.wrap_method( + self.delete_processor, + default_timeout=None, + client_info=client_info, + ), + self.enable_processor: gapic_v1.method.wrap_method( + self.enable_processor, + default_timeout=None, + client_info=client_info, + ), + self.disable_processor: gapic_v1.method.wrap_method( + self.disable_processor, + default_timeout=None, + client_info=client_info, + ), + self.set_default_processor_version: gapic_v1.method.wrap_method( + self.set_default_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.review_document: gapic_v1.method.wrap_method( + self.review_document, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + 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): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + Union[ + document_processor_service.ProcessResponse, + Awaitable[document_processor_service.ProcessResponse] + ]]: + raise NotImplementedError() + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + Union[ + document_processor_service.FetchProcessorTypesResponse, + Awaitable[document_processor_service.FetchProcessorTypesResponse] + ]]: + raise NotImplementedError() + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + Union[ + document_processor_service.ListProcessorTypesResponse, + Awaitable[document_processor_service.ListProcessorTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + Union[ + processor_type.ProcessorType, + Awaitable[processor_type.ProcessorType] + ]]: + raise NotImplementedError() + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + Union[ + document_processor_service.ListProcessorsResponse, + Awaitable[document_processor_service.ListProcessorsResponse] + ]]: + raise NotImplementedError() + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + Union[ + processor.Processor, + Awaitable[processor.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) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + Union[ + processor.ProcessorVersion, + Awaitable[processor.ProcessorVersion] + ]]: + raise NotImplementedError() + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + Union[ + document_processor_service.ListProcessorVersionsResponse, + Awaitable[document_processor_service.ListProcessorVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + Union[ + gcd_processor.Processor, + Awaitable[gcd_processor.Processor] + ]]: + raise NotImplementedError() + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DocumentProcessorServiceTransport', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py new file mode 100644 index 00000000..05918993 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py @@ -0,0 +1,945 @@ +# -*- 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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import 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 +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO + + +class DocumentProcessorServiceGrpcTransport(DocumentProcessorServiceTransport): + """gRPC backend transport for DocumentProcessorService. + + Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + document_processor_service.ProcessResponse]: + r"""Return a callable for the process document method over gRPC. + + Processes a single document. + + Returns: + Callable[[~.ProcessRequest], + ~.ProcessResponse]: + 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 'process_document' not in self._stubs: + self._stubs['process_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ProcessDocument', + request_serializer=document_processor_service.ProcessRequest.serialize, + response_deserializer=document_processor_service.ProcessResponse.deserialize, + ) + return self._stubs['process_document'] + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch process documents method over gRPC. + + LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + Returns: + Callable[[~.BatchProcessRequest], + ~.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 'batch_process_documents' not in self._stubs: + self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/BatchProcessDocuments', + request_serializer=document_processor_service.BatchProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_process_documents'] + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + document_processor_service.FetchProcessorTypesResponse]: + r"""Return a callable for the fetch processor types method over gRPC. + + Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + Returns: + Callable[[~.FetchProcessorTypesRequest], + ~.FetchProcessorTypesResponse]: + 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 'fetch_processor_types' not in self._stubs: + self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/FetchProcessorTypes', + request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, + ) + return self._stubs['fetch_processor_types'] + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + document_processor_service.ListProcessorTypesResponse]: + r"""Return a callable for the list processor types method over gRPC. + + Lists the processor types that exist. + + Returns: + Callable[[~.ListProcessorTypesRequest], + ~.ListProcessorTypesResponse]: + 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_processor_types' not in self._stubs: + self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorTypes', + request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, + ) + return self._stubs['list_processor_types'] + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + processor_type.ProcessorType]: + r"""Return a callable for the get processor type method over gRPC. + + Gets a processor type detail. + + Returns: + Callable[[~.GetProcessorTypeRequest], + ~.ProcessorType]: + 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_processor_type' not in self._stubs: + self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorType', + request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, + response_deserializer=processor_type.ProcessorType.deserialize, + ) + return self._stubs['get_processor_type'] + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + document_processor_service.ListProcessorsResponse]: + r"""Return a callable for the list processors method over gRPC. + + Lists all processors which belong to this project. + + Returns: + Callable[[~.ListProcessorsRequest], + ~.ListProcessorsResponse]: + 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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessors', + request_serializer=document_processor_service.ListProcessorsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + processor.Processor]: + r"""Return a callable for the get processor method over gRPC. + + Gets a processor detail. + + Returns: + Callable[[~.GetProcessorRequest], + ~.Processor]: + 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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessor', + request_serializer=document_processor_service.GetProcessorRequest.serialize, + response_deserializer=processor.Processor.deserialize, + ) + 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) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + processor.ProcessorVersion]: + r"""Return a callable for the get processor version method over gRPC. + + Gets a processor version detail. + + Returns: + Callable[[~.GetProcessorVersionRequest], + ~.ProcessorVersion]: + 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_processor_version' not in self._stubs: + self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorVersion', + request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, + response_deserializer=processor.ProcessorVersion.deserialize, + ) + return self._stubs['get_processor_version'] + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + document_processor_service.ListProcessorVersionsResponse]: + r"""Return a callable for the list processor versions method over gRPC. + + Lists all versions of a processor. + + Returns: + Callable[[~.ListProcessorVersionsRequest], + ~.ListProcessorVersionsResponse]: + 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_processor_versions' not in self._stubs: + self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorVersions', + request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, + ) + return self._stubs['list_processor_versions'] + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete processor version method over gRPC. + + Deletes the processor version, all artifacts under + the processor version will be deleted. + + Returns: + Callable[[~.DeleteProcessorVersionRequest], + ~.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 'delete_processor_version' not in self._stubs: + self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessorVersion', + request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor_version'] + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the deploy processor version method over gRPC. + + Deploys the processor version. + + Returns: + Callable[[~.DeployProcessorVersionRequest], + ~.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 'deploy_processor_version' not in self._stubs: + self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeployProcessorVersion', + request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_processor_version'] + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the undeploy processor version method over gRPC. + + Undeploys the processor version. + + Returns: + Callable[[~.UndeployProcessorVersionRequest], + ~.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 'undeploy_processor_version' not in self._stubs: + self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/UndeployProcessorVersion', + request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_processor_version'] + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + gcd_processor.Processor]: + r"""Return a callable for the create processor method over gRPC. + + Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + Returns: + Callable[[~.CreateProcessorRequest], + ~.Processor]: + 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 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/CreateProcessor', + request_serializer=document_processor_service.CreateProcessorRequest.serialize, + response_deserializer=gcd_processor.Processor.deserialize, + ) + return self._stubs['create_processor'] + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + ~.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 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessor', + request_serializer=document_processor_service.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the enable processor method over gRPC. + + Enables a processor + + Returns: + Callable[[~.EnableProcessorRequest], + ~.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 'enable_processor' not in self._stubs: + self._stubs['enable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/EnableProcessor', + request_serializer=document_processor_service.EnableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['enable_processor'] + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the disable processor method over gRPC. + + Disables a processor + + Returns: + Callable[[~.DisableProcessorRequest], + ~.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 'disable_processor' not in self._stubs: + self._stubs['disable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DisableProcessor', + request_serializer=document_processor_service.DisableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['disable_processor'] + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the set default processor version method over gRPC. + + Set the default (active) version of a + [Processor][google.cloud.documentai.v1beta3.Processor] that will + be used in + [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. + + Returns: + Callable[[~.SetDefaultProcessorVersionRequest], + ~.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 'set_default_processor_version' not in self._stubs: + self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/SetDefaultProcessorVersion', + request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_default_processor_version'] + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the review document method over gRPC. + + Send a document for Human Review. The input document + should be processed by the specified processor. + + Returns: + Callable[[~.ReviewDocumentRequest], + ~.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 'review_document' not in self._stubs: + self._stubs['review_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ReviewDocument', + request_serializer=document_processor_service.ReviewDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DocumentProcessorServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..5b7c532c --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py @@ -0,0 +1,944 @@ +# -*- 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. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +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 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 +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentProcessorServiceGrpcTransport + + +class DocumentProcessorServiceGrpcAsyncIOTransport(DocumentProcessorServiceTransport): + """gRPC AsyncIO backend transport for DocumentProcessorService. + + Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + Awaitable[document_processor_service.ProcessResponse]]: + r"""Return a callable for the process document method over gRPC. + + Processes a single document. + + Returns: + Callable[[~.ProcessRequest], + Awaitable[~.ProcessResponse]]: + 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 'process_document' not in self._stubs: + self._stubs['process_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ProcessDocument', + request_serializer=document_processor_service.ProcessRequest.serialize, + response_deserializer=document_processor_service.ProcessResponse.deserialize, + ) + return self._stubs['process_document'] + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch process documents method over gRPC. + + LRO endpoint to batch process many documents. The output is + written to Cloud Storage as JSON in the [Document] format. + + Returns: + Callable[[~.BatchProcessRequest], + 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 'batch_process_documents' not in self._stubs: + self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/BatchProcessDocuments', + request_serializer=document_processor_service.BatchProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_process_documents'] + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + Awaitable[document_processor_service.FetchProcessorTypesResponse]]: + r"""Return a callable for the fetch processor types method over gRPC. + + Fetches processor types. Note that we do not use + ListProcessorTypes here because it is not paginated. + + Returns: + Callable[[~.FetchProcessorTypesRequest], + Awaitable[~.FetchProcessorTypesResponse]]: + 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 'fetch_processor_types' not in self._stubs: + self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/FetchProcessorTypes', + request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, + ) + return self._stubs['fetch_processor_types'] + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + Awaitable[document_processor_service.ListProcessorTypesResponse]]: + r"""Return a callable for the list processor types method over gRPC. + + Lists the processor types that exist. + + Returns: + Callable[[~.ListProcessorTypesRequest], + Awaitable[~.ListProcessorTypesResponse]]: + 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_processor_types' not in self._stubs: + self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorTypes', + request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, + response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, + ) + return self._stubs['list_processor_types'] + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + Awaitable[processor_type.ProcessorType]]: + r"""Return a callable for the get processor type method over gRPC. + + Gets a processor type detail. + + Returns: + Callable[[~.GetProcessorTypeRequest], + Awaitable[~.ProcessorType]]: + 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_processor_type' not in self._stubs: + self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorType', + request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, + response_deserializer=processor_type.ProcessorType.deserialize, + ) + return self._stubs['get_processor_type'] + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + Awaitable[document_processor_service.ListProcessorsResponse]]: + r"""Return a callable for the list processors method over gRPC. + + Lists all processors which belong to this project. + + Returns: + Callable[[~.ListProcessorsRequest], + Awaitable[~.ListProcessorsResponse]]: + 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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessors', + request_serializer=document_processor_service.ListProcessorsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + Awaitable[processor.Processor]]: + r"""Return a callable for the get processor method over gRPC. + + Gets a processor detail. + + Returns: + Callable[[~.GetProcessorRequest], + Awaitable[~.Processor]]: + 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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessor', + request_serializer=document_processor_service.GetProcessorRequest.serialize, + response_deserializer=processor.Processor.deserialize, + ) + 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) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + Awaitable[processor.ProcessorVersion]]: + r"""Return a callable for the get processor version method over gRPC. + + Gets a processor version detail. + + Returns: + Callable[[~.GetProcessorVersionRequest], + Awaitable[~.ProcessorVersion]]: + 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_processor_version' not in self._stubs: + self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorVersion', + request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, + response_deserializer=processor.ProcessorVersion.deserialize, + ) + return self._stubs['get_processor_version'] + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + Awaitable[document_processor_service.ListProcessorVersionsResponse]]: + r"""Return a callable for the list processor versions method over gRPC. + + Lists all versions of a processor. + + Returns: + Callable[[~.ListProcessorVersionsRequest], + Awaitable[~.ListProcessorVersionsResponse]]: + 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_processor_versions' not in self._stubs: + self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorVersions', + request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, + response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, + ) + return self._stubs['list_processor_versions'] + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete processor version method over gRPC. + + Deletes the processor version, all artifacts under + the processor version will be deleted. + + Returns: + Callable[[~.DeleteProcessorVersionRequest], + 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 'delete_processor_version' not in self._stubs: + self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessorVersion', + request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor_version'] + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the deploy processor version method over gRPC. + + Deploys the processor version. + + Returns: + Callable[[~.DeployProcessorVersionRequest], + 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 'deploy_processor_version' not in self._stubs: + self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeployProcessorVersion', + request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_processor_version'] + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the undeploy processor version method over gRPC. + + Undeploys the processor version. + + Returns: + Callable[[~.UndeployProcessorVersionRequest], + 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 'undeploy_processor_version' not in self._stubs: + self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/UndeployProcessorVersion', + request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_processor_version'] + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + Awaitable[gcd_processor.Processor]]: + r"""Return a callable for the create processor method over gRPC. + + Creates a processor from the type processor that the + user chose. The processor will be at "ENABLED" state by + default after its creation. + + Returns: + Callable[[~.CreateProcessorRequest], + Awaitable[~.Processor]]: + 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 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/CreateProcessor', + request_serializer=document_processor_service.CreateProcessorRequest.serialize, + response_deserializer=gcd_processor.Processor.deserialize, + ) + return self._stubs['create_processor'] + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes the processor, unloads all deployed model + artifacts if it was enabled and then deletes all + artifacts associated with this processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + 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 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessor', + request_serializer=document_processor_service.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the enable processor method over gRPC. + + Enables a processor + + Returns: + Callable[[~.EnableProcessorRequest], + 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 'enable_processor' not in self._stubs: + self._stubs['enable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/EnableProcessor', + request_serializer=document_processor_service.EnableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['enable_processor'] + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the disable processor method over gRPC. + + Disables a processor + + Returns: + Callable[[~.DisableProcessorRequest], + 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 'disable_processor' not in self._stubs: + self._stubs['disable_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/DisableProcessor', + request_serializer=document_processor_service.DisableProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['disable_processor'] + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set default processor version method over gRPC. + + Set the default (active) version of a + [Processor][google.cloud.documentai.v1beta3.Processor] that will + be used in + [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] + and + [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. + + Returns: + Callable[[~.SetDefaultProcessorVersionRequest], + 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 'set_default_processor_version' not in self._stubs: + self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/SetDefaultProcessorVersion', + request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_default_processor_version'] + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the review document method over gRPC. + + Send a document for Human Review. The input document + should be processed by the specified processor. + + Returns: + Callable[[~.ReviewDocumentRequest], + 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 'review_document' not in self._stubs: + self._stubs['review_document'] = self.grpc_channel.unary_unary( + '/google.cloud.documentai.v1beta3.DocumentProcessorService/ReviewDocument', + request_serializer=document_processor_service.ReviewDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'DocumentProcessorServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py new file mode 100644 index 00000000..897873a3 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py @@ -0,0 +1,3280 @@ +# -*- 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 google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import 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 +from google.longrunning import operations_pb2 # type: ignore + +from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DocumentProcessorServiceRestInterceptor: + """Interceptor for DocumentProcessorService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the DocumentProcessorServiceRestTransport. + + .. code-block:: python + class MyCustomDocumentProcessorServiceInterceptor(DocumentProcessorServiceRestInterceptor): + def pre_batch_process_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_process_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_deploy_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_deploy_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_disable_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_enable_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_evaluate_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_evaluate_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_processor_types(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_processor_types(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor_type(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processor_types(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processor_types(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processor_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processor_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_process_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_process_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_review_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_review_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_default_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_default_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_train_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_train_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undeploy_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undeploy_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DocumentProcessorServiceRestTransport(interceptor=MyCustomDocumentProcessorServiceInterceptor()) + client = DocumentProcessorServiceClient(transport=transport) + + + """ + def pre_batch_process_documents(self, request: document_processor_service.BatchProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.BatchProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_process_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_batch_process_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_process_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_create_processor(self, request: document_processor_service.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.CreateProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_create_processor(self, response: gcd_processor.Processor) -> gcd_processor.Processor: + """Post-rpc interceptor for create_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_delete_processor(self, request: document_processor_service.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_delete_processor_version(self, request: document_processor_service.DeleteProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_delete_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_deploy_processor_version(self, request: document_processor_service.DeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for deploy_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_deploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for deploy_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_disable_processor(self, request: document_processor_service.DisableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DisableProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for disable_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_disable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for disable_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_enable_processor(self, request: document_processor_service.EnableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EnableProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for enable_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_enable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for enable_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_evaluate_processor_version(self, request: document_processor_service.EvaluateProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EvaluateProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for evaluate_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_evaluate_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for evaluate_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_fetch_processor_types(self, request: document_processor_service.FetchProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.FetchProcessorTypesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for fetch_processor_types + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_fetch_processor_types(self, response: document_processor_service.FetchProcessorTypesResponse) -> document_processor_service.FetchProcessorTypesResponse: + """Post-rpc interceptor for fetch_processor_types + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_evaluation(self, request: document_processor_service.GetEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_evaluation(self, response: evaluation.Evaluation) -> evaluation.Evaluation: + """Post-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_processor(self, request: document_processor_service.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_processor(self, response: processor.Processor) -> processor.Processor: + """Post-rpc interceptor for get_processor + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_processor_type(self, request: document_processor_service.GetProcessorTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorTypeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_processor_type(self, response: processor_type.ProcessorType) -> processor_type.ProcessorType: + """Post-rpc interceptor for get_processor_type + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_processor_version(self, request: document_processor_service.GetProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_processor_version(self, response: processor.ProcessorVersion) -> processor.ProcessorVersion: + """Post-rpc interceptor for get_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_evaluations(self, request: document_processor_service.ListEvaluationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_evaluations(self, response: document_processor_service.ListEvaluationsResponse) -> document_processor_service.ListEvaluationsResponse: + """Post-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_processors(self, request: document_processor_service.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_processors(self, response: document_processor_service.ListProcessorsResponse) -> document_processor_service.ListProcessorsResponse: + """Post-rpc interceptor for list_processors + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_processor_types(self, request: document_processor_service.ListProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorTypesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processor_types + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_processor_types(self, response: document_processor_service.ListProcessorTypesResponse) -> document_processor_service.ListProcessorTypesResponse: + """Post-rpc interceptor for list_processor_types + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_processor_versions(self, request: document_processor_service.ListProcessorVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorVersionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processor_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_processor_versions(self, response: document_processor_service.ListProcessorVersionsResponse) -> document_processor_service.ListProcessorVersionsResponse: + """Post-rpc interceptor for list_processor_versions + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_process_document(self, request: document_processor_service.ProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for process_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_process_document(self, response: document_processor_service.ProcessResponse) -> document_processor_service.ProcessResponse: + """Post-rpc interceptor for process_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_review_document(self, request: document_processor_service.ReviewDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ReviewDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for review_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_review_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for review_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_set_default_processor_version(self, request: document_processor_service.SetDefaultProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.SetDefaultProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_default_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_set_default_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for set_default_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_train_processor_version(self, request: document_processor_service.TrainProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.TrainProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for train_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_train_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for train_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_undeploy_processor_version(self, request: document_processor_service.UndeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.UndeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undeploy_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_undeploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for undeploy_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + + def pre_get_location(self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.Location: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_location(self, response: locations_pb2.GetLocationRequest) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_locations(self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.ListLocationsResponse: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_locations(self, response: locations_pb2.ListLocationsRequest) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation(self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]]) -> None: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_cancel_operation(self, response: operations_pb2.CancelOperationRequest) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_operation(self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_operation(self, response: operations_pb2.GetOperationRequest) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_operations(self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.ListOperationsResponse: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_operations(self, response: operations_pb2.ListOperationsRequest) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DocumentProcessorServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DocumentProcessorServiceRestInterceptor + + +class DocumentProcessorServiceRestTransport(DocumentProcessorServiceTransport): + """REST backend transport for DocumentProcessorService. + + Service to call Cloud DocumentAI to process documents + according to the processor's definition. Processors are built + using state-of-the-art Google AI such as natural language, + computer vision, and translation to extract structured + information from unstructured or semi-structured documents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'documentai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[DocumentProcessorServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DocumentProcessorServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', + }, + { + 'method': 'post', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', + }, + { + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta3") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _BatchProcessDocuments(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("BatchProcessDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.BatchProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch process documents method over HTTP. + + Args: + request (~.document_processor_service.BatchProcessRequest): + The request object. Request message for batch process + document method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:batchProcess', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:batchProcess', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_process_documents(request, metadata) + pb_request = document_processor_service.BatchProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_process_documents(resp) + return resp + + class _CreateProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("CreateProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.CreateProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_processor.Processor: + r"""Call the create processor method over HTTP. + + Args: + request (~.document_processor_service.CreateProcessorRequest): + The request object. Request message for create a + processor. Notice this request is sent + to a regionalized backend service, and + if the processor type is not available + on that region, the creation will fail. + + 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: + ~.gcd_processor.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{parent=projects/*/locations/*}/processors', + 'body': 'processor', + }, + ] + request, metadata = self._interceptor.pre_create_processor(request, metadata) + pb_request = document_processor_service.CreateProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_processor.Processor() + pb_resp = gcd_processor.Processor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_processor(resp) + return resp + + class _DeleteProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DeleteProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DeleteProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete processor method over HTTP. + + Args: + request (~.document_processor_service.DeleteProcessorRequest): + The request object. Request message for the delete + processor method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_processor(request, metadata) + pb_request = document_processor_service.DeleteProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_processor(resp) + return resp + + class _DeleteProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DeleteProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DeleteProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete processor version method over HTTP. + + Args: + request (~.document_processor_service.DeleteProcessorVersionRequest): + The request object. Request message for the delete + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_processor_version(request, metadata) + pb_request = document_processor_service.DeleteProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_processor_version(resp) + return resp + + class _DeployProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DeployProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DeployProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the deploy processor version method over HTTP. + + Args: + request (~.document_processor_service.DeployProcessorVersionRequest): + The request object. Request message for the deploy + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_deploy_processor_version(request, metadata) + pb_request = document_processor_service.DeployProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_deploy_processor_version(resp) + return resp + + class _DisableProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("DisableProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.DisableProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the disable processor method over HTTP. + + Args: + request (~.document_processor_service.DisableProcessorRequest): + The request object. Request message for the disable + processor method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:disable', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_disable_processor(request, metadata) + pb_request = document_processor_service.DisableProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_disable_processor(resp) + return resp + + class _EnableProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("EnableProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.EnableProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the enable processor method over HTTP. + + Args: + request (~.document_processor_service.EnableProcessorRequest): + The request object. Request message for the enable + processor method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:enable', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_enable_processor(request, metadata) + pb_request = document_processor_service.EnableProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_enable_processor(resp) + return resp + + class _EvaluateProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("EvaluateProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.EvaluateProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the evaluate processor + version method over HTTP. + + Args: + request (~.document_processor_service.EvaluateProcessorVersionRequest): + The request object. Evaluates the given ProcessorVersion + against the supplied documents. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_evaluate_processor_version(request, metadata) + pb_request = document_processor_service.EvaluateProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_evaluate_processor_version(resp) + return resp + + class _FetchProcessorTypes(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("FetchProcessorTypes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.FetchProcessorTypesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.FetchProcessorTypesResponse: + r"""Call the fetch processor types method over HTTP. + + Args: + request (~.document_processor_service.FetchProcessorTypesRequest): + The request object. Request message for fetch processor + types. + + 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: + ~.document_processor_service.FetchProcessorTypesResponse: + Response message for fetch processor + types. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{parent=projects/*/locations/*}:fetchProcessorTypes', + }, + ] + request, metadata = self._interceptor.pre_fetch_processor_types(request, metadata) + pb_request = document_processor_service.FetchProcessorTypesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.FetchProcessorTypesResponse() + pb_resp = document_processor_service.FetchProcessorTypesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_processor_types(resp) + return resp + + class _GetEvaluation(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetEvaluation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetEvaluationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> evaluation.Evaluation: + r"""Call the get evaluation method over HTTP. + + Args: + request (~.document_processor_service.GetEvaluationRequest): + The request object. Retrieves a specific Evaluation. + 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: + ~.evaluation.Evaluation: + An evaluation of a ProcessorVersion's + performance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_evaluation(request, metadata) + pb_request = document_processor_service.GetEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.Evaluation() + pb_resp = evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_evaluation(resp) + return resp + + class _GetProcessor(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> processor.Processor: + r"""Call the get processor method over HTTP. + + Args: + request (~.document_processor_service.GetProcessorRequest): + The request object. Request message for get processor. + 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: + ~.processor.Processor: + The first-class citizen for Document + AI. Each processor defines how to + extract structural information from a + document. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor(request, metadata) + pb_request = document_processor_service.GetProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = processor.Processor() + pb_resp = processor.Processor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor(resp) + return resp + + class _GetProcessorType(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetProcessorType") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetProcessorTypeRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> processor_type.ProcessorType: + r"""Call the get processor type method over HTTP. + + Args: + request (~.document_processor_service.GetProcessorTypeRequest): + The request object. Request message for get processor. + 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: + ~.processor_type.ProcessorType: + A processor type is responsible for + performing a certain document + understanding task on a certain type of + document. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/processorTypes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor_type(request, metadata) + pb_request = document_processor_service.GetProcessorTypeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = processor_type.ProcessorType() + pb_resp = processor_type.ProcessorType.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor_type(resp) + return resp + + class _GetProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.GetProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> processor.ProcessorVersion: + r"""Call the get processor version method over HTTP. + + Args: + request (~.document_processor_service.GetProcessorVersionRequest): + The request object. Request message for get processor + version. + + 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: + ~.processor.ProcessorVersion: + A processor version is an + implementation of a processor. Each + processor can have multiple versions, + pre-trained by Google internally or + up-trained by the customer. At a time, a + processor can only have one default + version version. So the processor's + behavior (when processing documents) is + defined by a default version + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor_version(request, metadata) + pb_request = document_processor_service.GetProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = processor.ProcessorVersion() + pb_resp = processor.ProcessorVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor_version(resp) + return resp + + class _ListEvaluations(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListEvaluations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListEvaluationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListEvaluationsResponse: + r"""Call the list evaluations method over HTTP. + + Args: + request (~.document_processor_service.ListEvaluationsRequest): + The request object. Retrieves a list of evaluations for a + given ProcessorVersion. + + 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: + ~.document_processor_service.ListEvaluationsResponse: + The response from ListEvaluations. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations', + }, + ] + request, metadata = self._interceptor.pre_list_evaluations(request, metadata) + pb_request = document_processor_service.ListEvaluationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListEvaluationsResponse() + pb_resp = document_processor_service.ListEvaluationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_evaluations(resp) + return resp + + class _ListProcessors(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListProcessors") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListProcessorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListProcessorsResponse: + r"""Call the list processors method over HTTP. + + Args: + request (~.document_processor_service.ListProcessorsRequest): + The request object. Request message for list all + processors belongs to a project. + + 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: + ~.document_processor_service.ListProcessorsResponse: + Response message for list processors. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{parent=projects/*/locations/*}/processors', + }, + ] + request, metadata = self._interceptor.pre_list_processors(request, metadata) + pb_request = document_processor_service.ListProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListProcessorsResponse() + pb_resp = document_processor_service.ListProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processors(resp) + return resp + + class _ListProcessorTypes(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListProcessorTypes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListProcessorTypesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListProcessorTypesResponse: + r"""Call the list processor types method over HTTP. + + Args: + request (~.document_processor_service.ListProcessorTypesRequest): + The request object. Request message for list processor + types. + + 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: + ~.document_processor_service.ListProcessorTypesResponse: + Response message for list processor + types. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{parent=projects/*/locations/*}/processorTypes', + }, + ] + request, metadata = self._interceptor.pre_list_processor_types(request, metadata) + pb_request = document_processor_service.ListProcessorTypesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListProcessorTypesResponse() + pb_resp = document_processor_service.ListProcessorTypesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processor_types(resp) + return resp + + class _ListProcessorVersions(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListProcessorVersions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ListProcessorVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ListProcessorVersionsResponse: + r"""Call the list processor versions method over HTTP. + + Args: + request (~.document_processor_service.ListProcessorVersionsRequest): + The request object. Request message for list all + processor versions belongs to a + processor. + + 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: + ~.document_processor_service.ListProcessorVersionsResponse: + Response message for list processors. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions', + }, + ] + request, metadata = self._interceptor.pre_list_processor_versions(request, metadata) + pb_request = document_processor_service.ListProcessorVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListProcessorVersionsResponse() + pb_resp = document_processor_service.ListProcessorVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processor_versions(resp) + return resp + + class _ProcessDocument(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ProcessDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_processor_service.ProcessResponse: + r"""Call the process document method over HTTP. + + Args: + request (~.document_processor_service.ProcessRequest): + The request object. Request message for the process + document method. + + 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: + ~.document_processor_service.ProcessResponse: + Response message for the process + document method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:process', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:process', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_process_document(request, metadata) + pb_request = document_processor_service.ProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ProcessResponse() + pb_resp = document_processor_service.ProcessResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_process_document(resp) + return resp + + class _ReviewDocument(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ReviewDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.ReviewDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the review document method over HTTP. + + Args: + request (~.document_processor_service.ReviewDocumentRequest): + The request object. Request message for review document + method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_review_document(request, metadata) + pb_request = document_processor_service.ReviewDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_review_document(resp) + return resp + + class _SetDefaultProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("SetDefaultProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.SetDefaultProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the set default processor + version method over HTTP. + + Args: + request (~.document_processor_service.SetDefaultProcessorVersionRequest): + The request object. Request message for the set default + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{processor=projects/*/locations/*/processors/*}:setDefaultProcessorVersion', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_default_processor_version(request, metadata) + pb_request = document_processor_service.SetDefaultProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_default_processor_version(resp) + return resp + + class _TrainProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("TrainProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.TrainProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the train processor version method over HTTP. + + Args: + request (~.document_processor_service.TrainProcessorVersionRequest): + The request object. Request message for the create + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:train', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_train_processor_version(request, metadata) + pb_request = document_processor_service.TrainProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_train_processor_version(resp) + return resp + + class _UndeployProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("UndeployProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_processor_service.UndeployProcessorVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the undeploy processor + version method over HTTP. + + Args: + request (~.document_processor_service.UndeployProcessorVersionRequest): + The request object. Request message for the undeploy + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_undeploy_processor_version(request, metadata) + pb_request = document_processor_service.UndeployProcessorVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undeploy_processor_version(resp) + return resp + + @property + def batch_process_documents(self) -> Callable[ + [document_processor_service.BatchProcessRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchProcessDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_processor(self) -> Callable[ + [document_processor_service.CreateProcessorRequest], + gcd_processor.Processor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_processor(self) -> Callable[ + [document_processor_service.DeleteProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_processor_version(self) -> Callable[ + [document_processor_service.DeleteProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def deploy_processor_version(self) -> Callable[ + [document_processor_service.DeployProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def disable_processor(self) -> Callable[ + [document_processor_service.DisableProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DisableProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def enable_processor(self) -> Callable[ + [document_processor_service.EnableProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EnableProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def evaluate_processor_version(self) -> Callable[ + [document_processor_service.EvaluateProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EvaluateProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_processor_types(self) -> Callable[ + [document_processor_service.FetchProcessorTypesRequest], + document_processor_service.FetchProcessorTypesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchProcessorTypes(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation(self) -> Callable[ + [document_processor_service.GetEvaluationRequest], + evaluation.Evaluation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor(self) -> Callable[ + [document_processor_service.GetProcessorRequest], + processor.Processor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor_type(self) -> Callable[ + [document_processor_service.GetProcessorTypeRequest], + processor_type.ProcessorType]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessorType(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor_version(self) -> Callable[ + [document_processor_service.GetProcessorVersionRequest], + processor.ProcessorVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluations(self) -> Callable[ + [document_processor_service.ListEvaluationsRequest], + document_processor_service.ListEvaluationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processors(self) -> Callable[ + [document_processor_service.ListProcessorsRequest], + document_processor_service.ListProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processor_types(self) -> Callable[ + [document_processor_service.ListProcessorTypesRequest], + document_processor_service.ListProcessorTypesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessorTypes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processor_versions(self) -> Callable[ + [document_processor_service.ListProcessorVersionsRequest], + document_processor_service.ListProcessorVersionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessorVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def process_document(self) -> Callable[ + [document_processor_service.ProcessRequest], + document_processor_service.ProcessResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ProcessDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def review_document(self) -> Callable[ + [document_processor_service.ReviewDocumentRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReviewDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_default_processor_version(self) -> Callable[ + [document_processor_service.SetDefaultProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetDefaultProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def train_processor_version(self) -> Callable[ + [document_processor_service.TrainProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TrainProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def undeploy_processor_version(self) -> Callable[ + [document_processor_service.UndeployProcessorVersionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(DocumentProcessorServiceRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + 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: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*}', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(DocumentProcessorServiceRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + 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: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*}/locations', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(DocumentProcessorServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', + }, +{ + 'method': 'post', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(DocumentProcessorServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + 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: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(DocumentProcessorServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + 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: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', + }, +{ + 'method': 'get', + 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DocumentProcessorServiceRestTransport', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py new file mode 100644 index 00000000..57f2c6fe --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py @@ -0,0 +1,176 @@ +# -*- 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 .barcode import ( + Barcode, +) +from .document import ( + Document, +) +from .document_io import ( + BatchDocumentsInputConfig, + DocumentOutputConfig, + GcsDocument, + GcsDocuments, + GcsPrefix, + OcrConfig, + RawDocument, +) +from .document_processor_service import ( + BatchProcessMetadata, + BatchProcessRequest, + BatchProcessResponse, + CreateProcessorRequest, + DeleteProcessorMetadata, + DeleteProcessorRequest, + DeleteProcessorVersionMetadata, + DeleteProcessorVersionRequest, + DeployProcessorVersionMetadata, + DeployProcessorVersionRequest, + DeployProcessorVersionResponse, + DisableProcessorMetadata, + DisableProcessorRequest, + DisableProcessorResponse, + EnableProcessorMetadata, + EnableProcessorRequest, + EnableProcessorResponse, + EvaluateProcessorVersionMetadata, + EvaluateProcessorVersionRequest, + EvaluateProcessorVersionResponse, + FetchProcessorTypesRequest, + FetchProcessorTypesResponse, + GetEvaluationRequest, + GetProcessorRequest, + GetProcessorTypeRequest, + GetProcessorVersionRequest, + HumanReviewStatus, + ListEvaluationsRequest, + ListEvaluationsResponse, + ListProcessorsRequest, + ListProcessorsResponse, + ListProcessorTypesRequest, + ListProcessorTypesResponse, + ListProcessorVersionsRequest, + ListProcessorVersionsResponse, + ProcessOptions, + ProcessRequest, + ProcessResponse, + ReviewDocumentOperationMetadata, + ReviewDocumentRequest, + ReviewDocumentResponse, + SetDefaultProcessorVersionMetadata, + SetDefaultProcessorVersionRequest, + SetDefaultProcessorVersionResponse, + TrainProcessorVersionMetadata, + TrainProcessorVersionRequest, + TrainProcessorVersionResponse, + UndeployProcessorVersionMetadata, + UndeployProcessorVersionRequest, + UndeployProcessorVersionResponse, +) +from .document_schema import ( + DocumentSchema, +) +from .evaluation import ( + Evaluation, + EvaluationReference, +) +from .geometry import ( + BoundingPoly, + NormalizedVertex, + Vertex, +) +from .operation_metadata import ( + CommonOperationMetadata, +) +from .processor import ( + Processor, + ProcessorVersion, +) +from .processor_type import ( + ProcessorType, +) + +__all__ = ( + 'Barcode', + 'Document', + 'BatchDocumentsInputConfig', + 'DocumentOutputConfig', + 'GcsDocument', + 'GcsDocuments', + 'GcsPrefix', + 'OcrConfig', + 'RawDocument', + 'BatchProcessMetadata', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'CreateProcessorRequest', + 'DeleteProcessorMetadata', + 'DeleteProcessorRequest', + 'DeleteProcessorVersionMetadata', + 'DeleteProcessorVersionRequest', + 'DeployProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DisableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'EnableProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EvaluateProcessorVersionMetadata', + 'EvaluateProcessorVersionRequest', + 'EvaluateProcessorVersionResponse', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetEvaluationRequest', + 'GetProcessorRequest', + 'GetProcessorTypeRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListEvaluationsRequest', + 'ListEvaluationsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessOptions', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'TrainProcessorVersionMetadata', + 'TrainProcessorVersionRequest', + 'TrainProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + 'Evaluation', + 'EvaluationReference', + 'BoundingPoly', + 'NormalizedVertex', + 'Vertex', + 'CommonOperationMetadata', + 'Processor', + 'ProcessorVersion', + 'ProcessorType', +) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py new file mode 100644 index 00000000..4738df4a --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py @@ -0,0 +1,85 @@ +# -*- 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 + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'Barcode', + }, +) + + +class Barcode(proto.Message): + r"""Encodes the detailed information of a barcode. + + 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. + 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. + raw_value (str): + Raw value encoded in the barcode. For example: + ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. + """ + + format_: str = proto.Field( + proto.STRING, + number=1, + ) + value_format: str = proto.Field( + proto.STRING, + number=2, + ) + raw_value: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py new file mode 100644 index 00000000..6517064f --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py @@ -0,0 +1,1712 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.documentai_v1beta3.types import barcode as gcd_barcode +from google.cloud.documentai_v1beta3.types import geometry +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from google.type import money_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'Document', + }, +) + + +class Document(proto.Message): + r"""Document represents the canonical document resource in + Document AI. It is an interchange format that provides insights + into documents and allows for collaboration between users and + Document AI to iterate and optimize for quality. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Optional. Currently supports Google Cloud Storage URI of the + form ``gs://bucket_name/object_name``. Object versioning is + not supported. See `Google Cloud Storage Request + URIs `__ + for more info. + + This field is a member of `oneof`_ ``source``. + content (bytes): + Optional. Inline document content, represented as a stream + of bytes. Note: As with all ``bytes`` fields, protobuffers + use a pure binary representation, whereas JSON + representations use base64. + + This field is a member of `oneof`_ ``source``. + mime_type (str): + An IANA published MIME type (also referred to + as media type). For more information, see + https://www.iana.org/assignments/media-types/media-types.xhtml. + text (str): + Optional. UTF-8 encoded text in reading order + from the document. + text_styles (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Style]): + Styles for the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + pages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page]): + Visual page layout for the + [Document][google.cloud.documentai.v1beta3.Document]. + entities (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Entity]): + A list of entities detected on + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + For document shards, entities in this list may cross shard + boundaries. + entity_relations (MutableSequence[google.cloud.documentai_v1beta3.types.Document.EntityRelation]): + Placeholder. Relationship among + [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][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. + If the document is not sharded, this message is + not specified. + error (google.rpc.status_pb2.Status): + Any error that occurred while processing this + document. + revisions (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Revision]): + Placeholder. Revision history of this + document. + """ + + class ShardInfo(proto.Message): + r"""For a large document, sharding may be performed to produce + several document shards. Each document shard contains this field + to detail which shard it is. + + Attributes: + shard_index (int): + The 0-based index of this shard. + shard_count (int): + Total number of shards. + text_offset (int): + The index of the first character in + [Document.text][google.cloud.documentai.v1beta3.Document.text] + in the overall document global text. + """ + + shard_index: int = proto.Field( + proto.INT64, + number=1, + ) + shard_count: int = proto.Field( + proto.INT64, + number=2, + ) + text_offset: int = proto.Field( + proto.INT64, + number=3, + ) + + class Style(proto.Message): + r"""Annotation for common text style attributes. This adheres to + CSS conventions as much as possible. + + Attributes: + text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): + Text anchor indexing into the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + color (google.type.color_pb2.Color): + Text color. + background_color (google.type.color_pb2.Color): + Text background color. + font_weight (str): + Font weight. Possible values are normal, bold, bolder, and + lighter. https://www.w3schools.com/cssref/pr_font_weight.asp + text_style (str): + Text style. Possible values are normal, italic, and oblique. + https://www.w3schools.com/cssref/pr_font_font-style.asp + text_decoration (str): + Text decoration. Follows CSS standard. + 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): + r"""Font size with unit. + + Attributes: + size (float): + Font size for the text. + unit (str): + Unit for the font size. Follows CSS naming + (in, px, pt, etc.). + """ + + size: float = proto.Field( + proto.FLOAT, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=2, + message=color_pb2.Color, + ) + background_color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=3, + message=color_pb2.Color, + ) + font_weight: str = proto.Field( + proto.STRING, + number=4, + ) + text_style: str = proto.Field( + proto.STRING, + number=5, + ) + text_decoration: str = proto.Field( + proto.STRING, + number=6, + ) + font_size: 'Document.Style.FontSize' = proto.Field( + 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]. + + Attributes: + page_number (int): + 1-based index for current + [Page][google.cloud.documentai.v1beta3.Document.Page] in a + parent [Document][google.cloud.documentai.v1beta3.Document]. + Useful when a page is taken out of a + [Document][google.cloud.documentai.v1beta3.Document] for + individual processing. + image (google.cloud.documentai_v1beta3.types.Document.Page.Image): + Rendered image for this page. This image is + preprocessed to remove any skew, rotation, and + distortions such that the annotation bounding + boxes can be upright and axis-aligned. + transforms (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Matrix]): + Transformation matrices that were applied to the original + document image to produce + [Page.image][google.cloud.documentai.v1beta3.Document.Page.image]. + dimension (google.cloud.documentai_v1beta3.types.Document.Page.Dimension): + Physical dimension of the page. + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for the page. + detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + blocks (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Block]): + A list of visually detected text blocks on + the page. A block has a set of lines (collected + into paragraphs) that have a common line-spacing + and orientation. + paragraphs (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Paragraph]): + A list of visually detected text paragraphs + on the page. A collection of lines that a human + would perceive as a paragraph. + lines (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Line]): + A list of visually detected text lines on the + page. A collection of tokens that a human would + perceive as a line. + tokens (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Token]): + A list of visually detected tokens on the + page. + visual_elements (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.VisualElement]): + A list of detected non-text visual elements + e.g. checkbox, signature etc. on the page. + tables (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table]): + A list of visually detected tables on the + page. + form_fields (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.FormField]): + A list of visually detected form fields on + the page. + symbols (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Symbol]): + A list of visually detected symbols on the + 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. + """ + + class Dimension(proto.Message): + r"""Dimension for the page. + + Attributes: + width (float): + Page width. + height (float): + Page height. + unit (str): + Dimension unit. + """ + + width: float = proto.Field( + proto.FLOAT, + number=1, + ) + height: float = proto.Field( + proto.FLOAT, + number=2, + ) + unit: str = proto.Field( + proto.STRING, + number=3, + ) + + class Image(proto.Message): + r"""Rendered image contents for this page. + + Attributes: + content (bytes): + Raw byte content of the image. + mime_type (str): + Encoding mime type for the image. + width (int): + Width of the image in pixels. + height (int): + Height of the image in pixels. + """ + + content: bytes = proto.Field( + proto.BYTES, + number=1, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + width: int = proto.Field( + proto.INT32, + number=3, + ) + height: int = proto.Field( + proto.INT32, + number=4, + ) + + class Matrix(proto.Message): + r"""Representation for transformation matrix, intended to be + compatible and used with OpenCV format for image manipulation. + + Attributes: + rows (int): + Number of rows in the matrix. + cols (int): + Number of columns in the matrix. + type_ (int): + This encodes information about what data type the matrix + uses. For example, 0 (CV_8U) is an unsigned 8-bit image. For + the full list of OpenCV primitive data types, please refer + to + https://docs.opencv.org/4.3.0/d1/d1b/group__core__hal__interface.html + data (bytes): + The matrix data. + """ + + rows: int = proto.Field( + proto.INT32, + number=1, + ) + cols: int = proto.Field( + proto.INT32, + number=2, + ) + type_: int = proto.Field( + proto.INT32, + number=3, + ) + data: bytes = proto.Field( + proto.BYTES, + number=4, + ) + + class Layout(proto.Message): + r"""Visual element describing a layout unit on a page. + + Attributes: + text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): + Text anchor indexing into the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + confidence (float): + Confidence of the current + [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]``. + bounding_poly (google.cloud.documentai_v1beta3.types.BoundingPoly): + The bounding polygon for the + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout]. + orientation (google.cloud.documentai_v1beta3.types.Document.Page.Layout.Orientation): + Detected orientation for the + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout]. + """ + class Orientation(proto.Enum): + r"""Detected human reading orientation. + + Values: + ORIENTATION_UNSPECIFIED (0): + Unspecified orientation. + PAGE_UP (1): + Orientation is aligned with page up. + PAGE_RIGHT (2): + Orientation is aligned with page right. + Turn the head 90 degrees clockwise from upright + to read. + PAGE_DOWN (3): + Orientation is aligned with page down. + Turn the head 180 degrees from upright to read. + PAGE_LEFT (4): + Orientation is aligned with page left. + Turn the head 90 degrees counterclockwise from + upright to read. + """ + ORIENTATION_UNSPECIFIED = 0 + PAGE_UP = 1 + PAGE_RIGHT = 2 + PAGE_DOWN = 3 + PAGE_LEFT = 4 + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + bounding_poly: geometry.BoundingPoly = proto.Field( + proto.MESSAGE, + number=3, + message=geometry.BoundingPoly, + ) + orientation: 'Document.Page.Layout.Orientation' = proto.Field( + proto.ENUM, + number=4, + enum='Document.Page.Layout.Orientation', + ) + + class Block(proto.Message): + r"""A block has a set of lines (collected into paragraphs) that + have a common line-spacing and orientation. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [Block][google.cloud.documentai.v1beta3.Document.Page.Block]. + 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 annotation. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + class Paragraph(proto.Message): + r"""A collection of lines that a human would perceive as a + paragraph. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [Paragraph][google.cloud.documentai.v1beta3.Document.Page.Paragraph]. + 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 annotation. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + class Line(proto.Message): + r"""A collection of tokens that a human would perceive as a line. + Does not cross column boundaries, can be horizontal, vertical, + etc. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [Line][google.cloud.documentai.v1beta3.Document.Page.Line]. + 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 annotation. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + class Token(proto.Message): + r"""A detected token. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. + detected_break (google.cloud.documentai_v1beta3.types.Document.Page.Token.DetectedBreak): + Detected break at the end of a + [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. + 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 annotation. + """ + + class DetectedBreak(proto.Message): + r"""Detected break at the end of a + [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. + + Attributes: + type_ (google.cloud.documentai_v1beta3.types.Document.Page.Token.DetectedBreak.Type): + Detected break type. + """ + class Type(proto.Enum): + r"""Enum to denote the type of break found. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified break type. + SPACE (1): + A single whitespace. + WIDE_SPACE (2): + A wider whitespace. + HYPHEN (3): + A hyphen that indicates that a token has been + split across lines. + """ + TYPE_UNSPECIFIED = 0 + SPACE = 1 + WIDE_SPACE = 2 + HYPHEN = 3 + + type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( + proto.ENUM, + number=1, + enum='Document.Page.Token.DetectedBreak.Type', + ) + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Token.DetectedBreak', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=4, + message='Document.Provenance', + ) + + class Symbol(proto.Message): + r"""A detected symbol. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [Symbol][google.cloud.documentai.v1beta3.Document.Page.Symbol]. + detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + + class VisualElement(proto.Message): + r"""Detected non-text visual elements e.g. checkbox, signature + etc. on the page. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [VisualElement][google.cloud.documentai.v1beta3.Document.Page.VisualElement]. + type_ (str): + Type of the + [VisualElement][google.cloud.documentai.v1beta3.Document.Page.VisualElement]. + detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + + class Table(proto.Message): + r"""A table representation similar to HTML table structure. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [Table][google.cloud.documentai.v1beta3.Document.Page.Table]. + header_rows (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): + Header rows of the table. + body_rows (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): + Body rows of the table. + 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): + r"""A row of table cells. + + Attributes: + cells (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableCell]): + Cells that make up this row. + """ + + cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.Page.Table.TableCell', + ) + + class TableCell(proto.Message): + r"""A cell representation inside the table. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [TableCell][google.cloud.documentai.v1beta3.Document.Page.Table.TableCell]. + row_span (int): + How many rows this cell spans. + col_span (int): + How many columns this cell spans. + detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + row_span: int = proto.Field( + proto.INT32, + number=2, + ) + col_span: int = proto.Field( + proto.INT32, + number=3, + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.Table.TableRow', + ) + body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.Table.TableRow', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + 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. + + Attributes: + field_name (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for the + [FormField][google.cloud.documentai.v1beta3.Document.Page.FormField] + name. e.g. ``Address``, ``Email``, ``Grand total``, + ``Phone number``, etc. + field_value (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for the + [FormField][google.cloud.documentai.v1beta3.Document.Page.FormField] + value. + name_detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages for name + together with confidence. + value_detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages for value + together with confidence. + value_type (str): + If the value is non-textual, this field represents the type. + Current valid values are: + + - blank (this indicates the ``field_value`` is normal text) + - ``unfilled_checkbox`` + - ``filled_checkbox`` + corrected_key_text (str): + Created for Labeling UI to export key text. If corrections + were made to the text identified by the + ``field_name.text_anchor``, this field will contain the + correction. + corrected_value_text (str): + Created for Labeling UI to export value text. If corrections + were made to the text identified by the + ``field_value.text_anchor``, this field will contain the + correction. + provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): + The history of this annotation. + """ + + field_name: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + field_value: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Layout', + ) + name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + value_type: str = proto.Field( + proto.STRING, + number=5, + ) + corrected_key_text: str = proto.Field( + proto.STRING, + number=6, + ) + corrected_value_text: str = proto.Field( + proto.STRING, + number=7, + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=8, + message='Document.Provenance', + ) + + class DetectedBarcode(proto.Message): + r"""A detected barcode. + + Attributes: + layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): + [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] + for + [DetectedBarcode][google.cloud.documentai.v1beta3.Document.Page.DetectedBarcode]. + barcode (google.cloud.documentai_v1beta3.types.Barcode): + Detailed barcode information of the + [DetectedBarcode][google.cloud.documentai.v1beta3.Document.Page.DetectedBarcode]. + """ + + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + barcode: gcd_barcode.Barcode = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_barcode.Barcode, + ) + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + 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]``. + """ + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + 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, + ) + image: 'Document.Page.Image' = proto.Field( + proto.MESSAGE, + number=13, + message='Document.Page.Image', + ) + transforms: MutableSequence['Document.Page.Matrix'] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='Document.Page.Matrix', + ) + dimension: 'Document.Page.Dimension' = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Dimension', + ) + layout: 'Document.Page.Layout' = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Page.Layout', + ) + detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Document.Page.Block', + ) + paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Document.Page.Paragraph', + ) + lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Document.Page.Line', + ) + tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Document.Page.Token', + ) + visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Document.Page.VisualElement', + ) + tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Page.Table', + ) + form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='Document.Page.FormField', + ) + symbols: MutableSequence['Document.Page.Symbol'] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='Document.Page.Symbol', + ) + detected_barcodes: MutableSequence['Document.Page.DetectedBarcode'] = proto.RepeatedField( + 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, + message='Document.Provenance', + ) + + class Entity(proto.Message): + r"""An entity that could be a phrase in the text or a property + that belongs to the document. It is a known entity type, such as + a person, an organization, or location. + + Attributes: + text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): + Optional. Provenance of the entity. Text anchor indexing + into the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + type_ (str): + Required. Entity type from a schema e.g. ``Address``. + mention_text (str): + 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]``. + page_anchor (google.cloud.documentai_v1beta3.types.Document.PageAnchor): + Optional. Represents the provenance of this + entity wrt. the location on the page where it + was found. + id (str): + Optional. Canonical id. This will be a unique + value in the entity list for this document. + normalized_value (google.cloud.documentai_v1beta3.types.Document.Entity.NormalizedValue): + Optional. Normalized entity value. Absent if + the extracted value could not be converted or + the type (e.g. address) is not supported for + certain parsers. This field is also only + populated for certain supported document types. + properties (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Entity]): + Optional. Entities can be nested to form a + hierarchical data structure representing the + content in the document. + provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): + Optional. The history of this annotation. + redacted (bool): + Optional. Whether the entity will be redacted + for de-identification purposes. + """ + + class NormalizedValue(proto.Message): + r"""Parsed and normalized entity value. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + money_value (google.type.money_pb2.Money): + Money value. See also: + https://github.com/googleapis/googleapis/blob/master/google/type/money.proto + + This field is a member of `oneof`_ ``structured_value``. + date_value (google.type.date_pb2.Date): + Date value. Includes year, month, day. See + also: + https://github.com/googleapis/googleapis/blob/master/google/type/date.proto + + This field is a member of `oneof`_ ``structured_value``. + datetime_value (google.type.datetime_pb2.DateTime): + DateTime value. Includes date, time, and + timezone. See also: + https://github.com/googleapis/googleapis/blob/master/google/type/datetime.proto + + This field is a member of `oneof`_ ``structured_value``. + address_value (google.type.postal_address_pb2.PostalAddress): + Postal address. See also: + https://github.com/googleapis/googleapis/blob/master/google/type/postal_address.proto + + This field is a member of `oneof`_ ``structured_value``. + boolean_value (bool): + Boolean value. Can be used for entities with + binary values, or for checkboxes. + + This field is a member of `oneof`_ ``structured_value``. + integer_value (int): + Integer value. + + This field is a member of `oneof`_ ``structured_value``. + float_value (float): + Float value. + + This field is a member of `oneof`_ ``structured_value``. + text (str): + Optional. An optional field to store a normalized string. + For some entity types, one of respective + ``structured_value`` fields may also be populated. Also not + all the types of ``structured_value`` will be normalized. + For example, some processors may not generate ``float`` or + ``integer`` normalized text by default. + + Below are sample formats mapped to structured values. + + - Money/Currency type (``money_value``) is in the ISO 4217 + text format. + - Date type (``date_value``) is in the ISO 8601 text + format. + - Datetime type (``datetime_value``) is in the ISO 8601 + text format. + """ + + money_value: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + oneof='structured_value', + message=money_pb2.Money, + ) + date_value: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + oneof='structured_value', + message=date_pb2.Date, + ) + datetime_value: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=4, + oneof='structured_value', + message=datetime_pb2.DateTime, + ) + address_value: postal_address_pb2.PostalAddress = proto.Field( + proto.MESSAGE, + number=5, + oneof='structured_value', + message=postal_address_pb2.PostalAddress, + ) + boolean_value: bool = proto.Field( + proto.BOOL, + number=6, + oneof='structured_value', + ) + integer_value: int = proto.Field( + proto.INT32, + number=7, + oneof='structured_value', + ) + float_value: float = proto.Field( + proto.FLOAT, + number=8, + oneof='structured_value', + ) + text: str = proto.Field( + proto.STRING, + number=1, + ) + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + mention_text: str = proto.Field( + proto.STRING, + number=3, + ) + mention_id: str = proto.Field( + proto.STRING, + number=4, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=5, + ) + page_anchor: 'Document.PageAnchor' = proto.Field( + proto.MESSAGE, + number=6, + message='Document.PageAnchor', + ) + id: str = proto.Field( + proto.STRING, + number=7, + ) + normalized_value: 'Document.Entity.NormalizedValue' = proto.Field( + proto.MESSAGE, + number=9, + message='Document.Entity.NormalizedValue', + ) + properties: MutableSequence['Document.Entity'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Entity', + ) + provenance: 'Document.Provenance' = proto.Field( + proto.MESSAGE, + number=11, + message='Document.Provenance', + ) + redacted: bool = proto.Field( + proto.BOOL, + number=12, + ) + + class EntityRelation(proto.Message): + r"""Relationship between + [Entities][google.cloud.documentai.v1beta3.Document.Entity]. + + Attributes: + subject_id (str): + Subject entity id. + object_id (str): + Object entity id. + relation (str): + Relationship description. + """ + + subject_id: str = proto.Field( + proto.STRING, + number=1, + ) + object_id: str = proto.Field( + proto.STRING, + number=2, + ) + relation: str = proto.Field( + proto.STRING, + number=3, + ) + + class TextAnchor(proto.Message): + r"""Text reference indexing into the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + + Attributes: + text_segments (MutableSequence[google.cloud.documentai_v1beta3.types.Document.TextAnchor.TextSegment]): + The text segments from the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + content (str): + Contains the content of the text span so that users do not + have to look it up in the text_segments. It is always + populated for formFields. + """ + + class TextSegment(proto.Message): + r"""A text segment in the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. The + indices may be out of bounds which indicate that the text extends + into another document shard for large sharded documents. See + [ShardInfo.text_offset][google.cloud.documentai.v1beta3.Document.ShardInfo.text_offset] + + Attributes: + start_index (int): + [TextSegment][google.cloud.documentai.v1beta3.Document.TextAnchor.TextSegment] + start UTF-8 char index in the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + end_index (int): + [TextSegment][google.cloud.documentai.v1beta3.Document.TextAnchor.TextSegment] + half open end UTF-8 char index in the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + """ + + start_index: int = proto.Field( + proto.INT64, + number=1, + ) + end_index: int = proto.Field( + proto.INT64, + number=2, + ) + + text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.TextAnchor.TextSegment', + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + class PageAnchor(proto.Message): + r"""Referencing the visual context of the entity in the + [Document.pages][google.cloud.documentai.v1beta3.Document.pages]. + Page anchors can be cross-page, consist of multiple bounding + polygons and optionally reference specific layout element types. + + Attributes: + page_refs (MutableSequence[google.cloud.documentai_v1beta3.types.Document.PageAnchor.PageRef]): + One or more references to visual page + elements + """ + + class PageRef(proto.Message): + r"""Represents a weak reference to a page element within a + document. + + Attributes: + page (int): + Required. Index into the + [Document.pages][google.cloud.documentai.v1beta3.Document.pages] + element, for example using + ``[Document.pages][page_refs.page]`` to locate the related + page element. This field is skipped when its value is the + default ``0``. See + https://developers.google.com/protocol-buffers/docs/proto3#json. + layout_type (google.cloud.documentai_v1beta3.types.Document.PageAnchor.PageRef.LayoutType): + Optional. The type of the layout element that + is being referenced if any. + layout_id (str): + Optional. Deprecated. Use + [PageRef.bounding_poly][google.cloud.documentai.v1beta3.Document.PageAnchor.PageRef.bounding_poly] + instead. + bounding_poly (google.cloud.documentai_v1beta3.types.BoundingPoly): + Optional. Identifies the bounding polygon of + a layout element on the page. + confidence (float): + Optional. Confidence of detected page element, if + applicable. Range ``[0, 1]``. + """ + class LayoutType(proto.Enum): + r"""The type of layout that is being referenced. + + Values: + LAYOUT_TYPE_UNSPECIFIED (0): + Layout Unspecified. + BLOCK (1): + References a + [Page.blocks][google.cloud.documentai.v1beta3.Document.Page.blocks] + element. + PARAGRAPH (2): + References a + [Page.paragraphs][google.cloud.documentai.v1beta3.Document.Page.paragraphs] + element. + LINE (3): + References a + [Page.lines][google.cloud.documentai.v1beta3.Document.Page.lines] + element. + TOKEN (4): + References a + [Page.tokens][google.cloud.documentai.v1beta3.Document.Page.tokens] + element. + VISUAL_ELEMENT (5): + References a + [Page.visual_elements][google.cloud.documentai.v1beta3.Document.Page.visual_elements] + element. + TABLE (6): + Refrrences a + [Page.tables][google.cloud.documentai.v1beta3.Document.Page.tables] + element. + FORM_FIELD (7): + References a + [Page.form_fields][google.cloud.documentai.v1beta3.Document.Page.form_fields] + element. + """ + LAYOUT_TYPE_UNSPECIFIED = 0 + BLOCK = 1 + PARAGRAPH = 2 + LINE = 3 + TOKEN = 4 + VISUAL_ELEMENT = 5 + TABLE = 6 + FORM_FIELD = 7 + + page: int = proto.Field( + proto.INT64, + number=1, + ) + layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( + proto.ENUM, + number=2, + enum='Document.PageAnchor.PageRef.LayoutType', + ) + layout_id: str = proto.Field( + proto.STRING, + number=3, + ) + bounding_poly: geometry.BoundingPoly = proto.Field( + proto.MESSAGE, + number=4, + message=geometry.BoundingPoly, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=5, + ) + + page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.PageAnchor.PageRef', + ) + + class Provenance(proto.Message): + r"""Structure to identify provenance relationships between + annotations in different revisions. + + Attributes: + revision (int): + The index of the revision that produced this + element. + id (int): + The Id of this operation. Needs to be unique + within the scope of the revision. + parents (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Provenance.Parent]): + References to the original elements that are + replaced. + type_ (google.cloud.documentai_v1beta3.types.Document.Provenance.OperationType): + The type of provenance operation. + """ + class OperationType(proto.Enum): + r"""If a processor or agent does an explicit operation on + existing elements. + + Values: + OPERATION_TYPE_UNSPECIFIED (0): + Operation type unspecified. If no operation is specified a + provenance entry is simply used to match against a + ``parent``. + ADD (1): + Add an element. + REMOVE (2): + Remove an element identified by ``parent``. + UPDATE (7): + Updates any fields within the given + provenance scope of the message. It 'overwrites' + the fields rather than replacing them. This is + especially relevant when we just want to update + a field value of an entity without also + affecting all the child properties. + REPLACE (3): + Currently unused. Replace an element identified by + ``parent``. + EVAL_REQUESTED (4): + Deprecated. Request human review for the element identified + by ``parent``. + EVAL_APPROVED (5): + Deprecated. Element is reviewed and approved + at human review, confidence will be set to 1.0. + EVAL_SKIPPED (6): + Deprecated. Element is skipped in the + validation process. + """ + OPERATION_TYPE_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + UPDATE = 7 + REPLACE = 3 + EVAL_REQUESTED = 4 + EVAL_APPROVED = 5 + EVAL_SKIPPED = 6 + + class Parent(proto.Message): + r"""The parent element the current element is based on. Used for + referencing/aligning, removal and replacement operations. + + Attributes: + revision (int): + The index of the index into current revision's parent_ids + list. + index (int): + The index of the parent item in the + corresponding item list (eg. list of entities, + properties within entities, etc.) in the parent + revision. + id (int): + The id of the parent provenance. + """ + + revision: int = proto.Field( + proto.INT32, + number=1, + ) + index: int = proto.Field( + proto.INT32, + number=3, + ) + id: int = proto.Field( + proto.INT32, + number=2, + ) + + revision: int = proto.Field( + proto.INT32, + number=1, + ) + id: int = proto.Field( + proto.INT32, + number=2, + ) + parents: MutableSequence['Document.Provenance.Parent'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance.Parent', + ) + type_: 'Document.Provenance.OperationType' = proto.Field( + proto.ENUM, + number=4, + enum='Document.Provenance.OperationType', + ) + + class Revision(proto.Message): + r"""Contains past or forward revisions of this document. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + agent (str): + If the change was made by a person specify + the name or id of that person. + + This field is a member of `oneof`_ ``source``. + processor (str): + If the annotation was made by processor + identify the processor by its resource name. + + This field is a member of `oneof`_ ``source``. + id (str): + Id of the revision, internally generated by + doc proto storage. Unique within the context of + the document. + parent (MutableSequence[int]): + The revisions that this revision is based on. This can + include one or more parent (when documents are merged.) This + field represents the index into the ``revisions`` field. + parent_ids (MutableSequence[str]): + The revisions that this revision is based on. Must include + all the ids that have anything to do with this revision - + eg. there are ``provenance.parent.revision`` fields that + index into this field. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the revision was created, + internally generated by doc proto storage at the + time of create. + human_review (google.cloud.documentai_v1beta3.types.Document.Revision.HumanReview): + Human Review information of this revision. + """ + + class HumanReview(proto.Message): + r"""Human Review information of the document. + + Attributes: + state (str): + Human review state. e.g. ``requested``, ``succeeded``, + ``rejected``. + state_message (str): + A message providing more details about the current state of + processing. For example, the rejection reason when the state + is ``rejected``. + """ + + state: str = proto.Field( + proto.STRING, + number=1, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + + agent: str = proto.Field( + proto.STRING, + number=4, + oneof='source', + ) + processor: str = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + id: str = proto.Field( + proto.STRING, + number=1, + ) + parent: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + parent_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + human_review: 'Document.Revision.HumanReview' = proto.Field( + proto.MESSAGE, + number=6, + message='Document.Revision.HumanReview', + ) + + class TextChange(proto.Message): + r"""This message is used for text changes aka. OCR corrections. + + Attributes: + text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): + Provenance of the correction. Text anchor indexing into the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + There can only be a single ``TextAnchor.text_segments`` + element. If the start and end index of the text segment are + the same, the text change is inserted before that index. + changed_text (str): + The text that replaces the text identified in the + ``text_anchor``. + provenance (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Provenance]): + The history of this annotation. + """ + + text_anchor: 'Document.TextAnchor' = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + changed_text: str = proto.Field( + proto.STRING, + number=2, + ) + provenance: MutableSequence['Document.Provenance'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + uri: str = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + content: bytes = proto.Field( + proto.BYTES, + number=2, + oneof='source', + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + text: str = proto.Field( + proto.STRING, + number=4, + ) + text_styles: MutableSequence[Style] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Style, + ) + pages: MutableSequence[Page] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Page, + ) + entities: MutableSequence[Entity] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Entity, + ) + entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=EntityRelation, + ) + text_changes: MutableSequence[TextChange] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=TextChange, + ) + shard_info: ShardInfo = proto.Field( + proto.MESSAGE, + number=9, + message=ShardInfo, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=10, + message=status_pb2.Status, + ) + revisions: MutableSequence[Revision] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=Revision, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py new file mode 100644 index 00000000..e194eeb2 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py @@ -0,0 +1,245 @@ +# -*- 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 + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'RawDocument', + 'GcsDocument', + 'GcsDocuments', + 'GcsPrefix', + 'BatchDocumentsInputConfig', + 'DocumentOutputConfig', + 'OcrConfig', + }, +) + + +class RawDocument(proto.Message): + r"""Payload message of raw document content (bytes). + + Attributes: + content (bytes): + Inline document content. + mime_type (str): + An IANA MIME type (RFC6838) indicating the nature and format + of the + [content][google.cloud.documentai.v1beta3.RawDocument.content]. + """ + + content: bytes = proto.Field( + proto.BYTES, + number=1, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GcsDocument(proto.Message): + r"""Specifies a document stored on Cloud Storage. + + Attributes: + gcs_uri (str): + The Cloud Storage object uri. + mime_type (str): + An IANA MIME type (RFC6838) of the content. + """ + + gcs_uri: str = proto.Field( + proto.STRING, + number=1, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GcsDocuments(proto.Message): + r"""Specifies a set of documents on Cloud Storage. + + Attributes: + documents (MutableSequence[google.cloud.documentai_v1beta3.types.GcsDocument]): + The list of documents. + """ + + documents: MutableSequence['GcsDocument'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GcsDocument', + ) + + +class GcsPrefix(proto.Message): + r"""Specifies all documents on Cloud Storage with a common + prefix. + + Attributes: + gcs_uri_prefix (str): + The URI prefix. + """ + + gcs_uri_prefix: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchDocumentsInputConfig(proto.Message): + r"""The common config to specify a set of documents used as + input. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (google.cloud.documentai_v1beta3.types.GcsPrefix): + The set of documents that match the specified Cloud Storage + ``gcs_prefix``. + + This field is a member of `oneof`_ ``source``. + gcs_documents (google.cloud.documentai_v1beta3.types.GcsDocuments): + The set of documents individually specified + on Cloud Storage. + + This field is a member of `oneof`_ ``source``. + """ + + gcs_prefix: 'GcsPrefix' = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsPrefix', + ) + gcs_documents: 'GcsDocuments' = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsDocuments', + ) + + +class DocumentOutputConfig(proto.Message): + r"""Config that controls the output of documents. All documents + will be written as a JSON file. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_output_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig.GcsOutputConfig): + Output config to write the results to Cloud + Storage. + + This field is a member of `oneof`_ ``destination``. + """ + + class GcsOutputConfig(proto.Message): + r"""The configuration used when outputting documents. + + Attributes: + gcs_uri (str): + The Cloud Storage uri (a directory) of the + output. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Specifies which fields to include in the output documents. + Only supports top level document and pages field so it must + be in the form of ``{document_field_name}`` or + ``pages.{page_field_name}``. + sharding_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig.GcsOutputConfig.ShardingConfig): + Specifies the sharding config for the output + document. + """ + + class ShardingConfig(proto.Message): + r"""The sharding config for the output document. + + Attributes: + pages_per_shard (int): + The number of pages per shard. + pages_overlap (int): + The number of overlapping pages between + consecutive shards. + """ + + pages_per_shard: int = proto.Field( + proto.INT32, + number=1, + ) + pages_overlap: int = proto.Field( + proto.INT32, + number=2, + ) + + gcs_uri: str = proto.Field( + proto.STRING, + number=1, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + sharding_config: 'DocumentOutputConfig.GcsOutputConfig.ShardingConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='DocumentOutputConfig.GcsOutputConfig.ShardingConfig', + ) + + gcs_output_config: GcsOutputConfig = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message=GcsOutputConfig, + ) + + +class OcrConfig(proto.Message): + r"""Config for Document OCR. + + Attributes: + enable_native_pdf_parsing (bool): + Enables special handling for PDFs with + existing text information. Results in better + text extraction quality in such PDF inputs. + advanced_ocr_options (MutableSequence[str]): + A list of advanced OCR options to further + fine-tune OCR behavior. + """ + + enable_native_pdf_parsing: bool = proto.Field( + proto.BOOL, + number=3, + ) + advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py new file mode 100644 index 00000000..dd08b224 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py @@ -0,0 +1,1534 @@ +# -*- 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 + +import proto # type: ignore + +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 document_schema as gcd_document_schema +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 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'ProcessOptions', + 'ProcessRequest', + 'HumanReviewStatus', + 'ProcessResponse', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'BatchProcessMetadata', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'GetProcessorTypeRequest', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'DeleteProcessorVersionRequest', + 'DeleteProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'CreateProcessorRequest', + 'DeleteProcessorRequest', + 'DeleteProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EnableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'DisableProcessorMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'SetDefaultProcessorVersionMetadata', + 'TrainProcessorVersionRequest', + 'TrainProcessorVersionResponse', + 'TrainProcessorVersionMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'ReviewDocumentOperationMetadata', + 'EvaluateProcessorVersionRequest', + 'EvaluateProcessorVersionMetadata', + 'EvaluateProcessorVersionResponse', + 'GetEvaluationRequest', + 'ListEvaluationsRequest', + 'ListEvaluationsResponse', + }, +) + + +class ProcessOptions(proto.Message): + r"""Options for Process API + + Attributes: + ocr_config (google.cloud.documentai_v1beta3.types.OcrConfig): + Only applicable to "Document OCR Processor". + Returns error if set on other processor types. + """ + + ocr_config: document_io.OcrConfig = proto.Field( + proto.MESSAGE, + number=1, + message=document_io.OcrConfig, + ) + + +class ProcessRequest(proto.Message): + r"""Request message for the process document method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_document (google.cloud.documentai_v1beta3.types.Document): + An inline document proto. + + This field is a member of `oneof`_ ``source``. + raw_document (google.cloud.documentai_v1beta3.types.RawDocument): + A raw document content (bytes). + + This field is a member of `oneof`_ ``source``. + name (str): + Required. The resource name of the + [Processor][google.cloud.documentai.v1beta3.Processor] or + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to use for processing. If a + [Processor][google.cloud.documentai.v1beta3.Processor] is + specified, the server will use its [default + version][google.cloud.documentai.v1beta3.Processor.default_processor_version]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + document (google.cloud.documentai_v1beta3.types.Document): + The document payload, the [content] and [mime_type] fields + must be set. + skip_human_review (bool): + 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. Only supports top level document and pages field + so it must be in the form of ``{document_field_name}`` or + ``pages.{page_field_name}``. + process_options (google.cloud.documentai_v1beta3.types.ProcessOptions): + Inference-time options for the process API + """ + + inline_document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + raw_document: document_io.RawDocument = proto.Field( + proto.MESSAGE, + number=5, + oneof='source', + message=document_io.RawDocument, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + skip_human_review: bool = proto.Field( + proto.BOOL, + number=3, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=6, + message=field_mask_pb2.FieldMask, + ) + process_options: 'ProcessOptions' = proto.Field( + proto.MESSAGE, + number=7, + message='ProcessOptions', + ) + + +class HumanReviewStatus(proto.Message): + r"""The status of human review on a processed document. + + Attributes: + state (google.cloud.documentai_v1beta3.types.HumanReviewStatus.State): + The state of human review on the processing + request. + state_message (str): + A message providing more details about the + human review state. + human_review_operation (str): + The name of the operation triggered by the processed + document. This field is populated only when the [state] is + [HUMAN_REVIEW_IN_PROGRESS]. It has the same response type + and metadata as the long running operation returned by + [ReviewDocument] method. + """ + class State(proto.Enum): + r"""The final state of human review on a processed document. + + Values: + STATE_UNSPECIFIED (0): + Human review state is unspecified. Most + likely due to an internal error. + SKIPPED (1): + Human review is skipped for the document. + This can happen because human review is not + enabled on the processor or the processing + request has been set to skip this document. + VALIDATION_PASSED (2): + Human review validation is triggered and + passed, so no review is needed. + IN_PROGRESS (3): + Human review validation is triggered and the + document is under review. + ERROR (4): + Some error happened during triggering human review, see the + [state_message] for details. + """ + STATE_UNSPECIFIED = 0 + SKIPPED = 1 + VALIDATION_PASSED = 2 + IN_PROGRESS = 3 + ERROR = 4 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + human_review_operation: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ProcessResponse(proto.Message): + r"""Response message for the process document method. + + Attributes: + document (google.cloud.documentai_v1beta3.types.Document): + The document payload, will populate fields + based on the processor's behavior. + human_review_operation (str): + The name of the operation triggered by the + processed document. If the human review process + is not triggered, this field will be empty. It + has the same response type and metadata as the + long running operation returned by + ReviewDocument method. + human_review_status (google.cloud.documentai_v1beta3.types.HumanReviewStatus): + The status of human review on the processed + document. + """ + + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + human_review_operation: str = proto.Field( + proto.STRING, + number=2, + ) + human_review_status: 'HumanReviewStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='HumanReviewStatus', + ) + + +class BatchProcessRequest(proto.Message): + r"""Request message for batch process document method. + + Attributes: + name (str): + Required. The resource name of + [Processor][google.cloud.documentai.v1beta3.Processor] or + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. + Format: + ``projects/{project}/locations/{location}/processors/{processor}``, + or + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + input_configs (MutableSequence[google.cloud.documentai_v1beta3.types.BatchProcessRequest.BatchInputConfig]): + The input config for each single document in + the batch process. + output_config (google.cloud.documentai_v1beta3.types.BatchProcessRequest.BatchOutputConfig): + The overall output config for batch process. + input_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): + The input documents for batch process. + document_output_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig): + The overall output config for batch process. + skip_human_review (bool): + Whether Human Review feature should be + skipped for this request. Default to false. + process_options (google.cloud.documentai_v1beta3.types.ProcessOptions): + Inference-time options for the process API + """ + + class BatchInputConfig(proto.Message): + r"""The message for input config in batch process. + + Attributes: + gcs_source (str): + The Cloud Storage location as the source of + the document. + mime_type (str): + Mimetype of the input. If the input is a raw document, the + supported mimetypes are application/pdf, image/tiff, and + image/gif. If the input is a [Document] proto, the type + should be application/json. + """ + + gcs_source: str = proto.Field( + proto.STRING, + number=1, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + + class BatchOutputConfig(proto.Message): + r"""The message for output config in batch process. + + Attributes: + gcs_destination (str): + The output Cloud Storage directory to put the + processed documents. + """ + + gcs_destination: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + input_configs: MutableSequence[BatchInputConfig] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=BatchInputConfig, + ) + output_config: BatchOutputConfig = proto.Field( + proto.MESSAGE, + number=3, + message=BatchOutputConfig, + ) + input_documents: document_io.BatchDocumentsInputConfig = proto.Field( + proto.MESSAGE, + number=5, + message=document_io.BatchDocumentsInputConfig, + ) + document_output_config: document_io.DocumentOutputConfig = proto.Field( + proto.MESSAGE, + number=6, + message=document_io.DocumentOutputConfig, + ) + skip_human_review: bool = proto.Field( + proto.BOOL, + number=4, + ) + process_options: 'ProcessOptions' = proto.Field( + proto.MESSAGE, + number=7, + message='ProcessOptions', + ) + + +class BatchProcessResponse(proto.Message): + r"""Response message for batch process document method. + """ + + +class BatchProcessMetadata(proto.Message): + r"""The long running operation metadata for batch process method. + + Attributes: + state (google.cloud.documentai_v1beta3.types.BatchProcessMetadata.State): + The state of the current batch processing. + state_message (str): + A message providing more details about the + current state of processing. For example, the + error message if the operation is failed. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update time of the operation. + individual_process_statuses (MutableSequence[google.cloud.documentai_v1beta3.types.BatchProcessMetadata.IndividualProcessStatus]): + The list of response details of each + document. + """ + class State(proto.Enum): + r"""Possible states of the batch processing operation. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + WAITING (1): + Request operation is waiting for scheduling. + RUNNING (2): + Request is being processed. + SUCCEEDED (3): + The batch processing completed successfully. + CANCELLING (4): + The batch processing was being cancelled. + CANCELLED (5): + The batch processing was cancelled. + FAILED (6): + The batch processing has failed. + """ + STATE_UNSPECIFIED = 0 + WAITING = 1 + RUNNING = 2 + SUCCEEDED = 3 + CANCELLING = 4 + CANCELLED = 5 + FAILED = 6 + + class IndividualProcessStatus(proto.Message): + r"""The status of a each individual document in the batch + process. + + Attributes: + input_gcs_source (str): + The source of the document, same as the [input_gcs_source] + field in the request when the batch process started. The + batch process is started by take snapshot of that document, + since a user can move or change that document during the + process. + status (google.rpc.status_pb2.Status): + The status processing the document. + output_gcs_destination (str): + The output_gcs_destination (in the request as + ``output_gcs_destination``) of the processed document if it + was successful, otherwise empty. + human_review_operation (str): + The name of the operation triggered by the + processed document. If the human review process + is not triggered, this field will be empty. It + has the same response type and metadata as the + long running operation returned by + ReviewDocument method. + human_review_status (google.cloud.documentai_v1beta3.types.HumanReviewStatus): + The status of human review on the processed + document. + """ + + input_gcs_source: str = proto.Field( + proto.STRING, + number=1, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + output_gcs_destination: str = proto.Field( + proto.STRING, + number=3, + ) + human_review_operation: str = proto.Field( + proto.STRING, + number=4, + ) + human_review_status: 'HumanReviewStatus' = proto.Field( + proto.MESSAGE, + number=5, + message='HumanReviewStatus', + ) + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + individual_process_statuses: MutableSequence[IndividualProcessStatus] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=IndividualProcessStatus, + ) + + +class FetchProcessorTypesRequest(proto.Message): + r"""Request message for fetch processor types. + + Attributes: + parent (str): + Required. The project of processor type to list. The + available processor types may depend on the allow-listing on + projects. Format: + ``projects/{project}/locations/{location}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchProcessorTypesResponse(proto.Message): + r"""Response message for fetch processor types. + + Attributes: + processor_types (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType]): + The list of processor types. + """ + + processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=processor_type.ProcessorType, + ) + + +class ListProcessorTypesRequest(proto.Message): + r"""Request message for list processor types. + + Attributes: + parent (str): + Required. The location of processor type to list. The + available processor types may depend on the allow-listing on + projects. Format: + ``projects/{project}/locations/{location}`` + page_size (int): + The maximum number of processor types to + return. If unspecified, at most 100 processor + types will be returned. The maximum value is + 500; values above 500 will be coerced to 500. + page_token (str): + Used to retrieve the next page of results, + empty if at the end of the list. + """ + + 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 ListProcessorTypesResponse(proto.Message): + r"""Response message for list processor types. + + Attributes: + processor_types (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType]): + The processor types. + next_page_token (str): + Points to the next page, otherwise empty. + """ + + @property + def raw_page(self): + return self + + processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=processor_type.ProcessorType, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListProcessorsRequest(proto.Message): + r"""Request message for list all processors belongs to a project. + + Attributes: + parent (str): + Required. The parent (project and location) which owns this + collection of Processors. Format: + ``projects/{project}/locations/{location}`` + page_size (int): + The maximum number of processors to return. + If unspecified, at most 50 processors will be + returned. The maximum value is 100; values above + 100 will be coerced to 100. + page_token (str): + We will return the processors sorted by + creation time. The page token will point to the + next processor. + """ + + 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 ListProcessorsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processors (MutableSequence[google.cloud.documentai_v1beta3.types.Processor]): + The list of processors. + next_page_token (str): + Points to the next processor, otherwise + empty. + """ + + @property + def raw_page(self): + return self + + processors: MutableSequence[gcd_processor.Processor] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.Processor, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetProcessorTypeRequest(proto.Message): + r"""Request message for get processor. + + Attributes: + name (str): + Required. The processor type resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetProcessorRequest(proto.Message): + r"""Request message for get processor. + + Attributes: + name (str): + Required. The processor resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetProcessorVersionRequest(proto.Message): + r"""Request message for get processor version. + + Attributes: + name (str): + Required. The processor resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProcessorVersionsRequest(proto.Message): + r"""Request message for list all processor versions belongs to a + processor. + + Attributes: + parent (str): + Required. The parent (project, location and processor) to + list all versions. Format: + ``projects/{project}/locations/{location}/processors/{processor}`` + page_size (int): + The maximum number of processor versions to + return. If unspecified, at most 10 processor + versions will be returned. The maximum value is + 20; values above 20 will be coerced to 20. + page_token (str): + We will return the processor versions sorted + by creation time. The page token will point to + the next processor version. + """ + + 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 ListProcessorVersionsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processor_versions (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorVersion]): + The list of processors. + next_page_token (str): + Points to the next processor, otherwise + empty. + """ + + @property + def raw_page(self): + return self + + processor_versions: MutableSequence[gcd_processor.ProcessorVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.ProcessorVersion, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteProcessorVersionRequest(proto.Message): + r"""Request message for the delete processor version method. + + Attributes: + name (str): + Required. The processor version resource name + to be deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for delete processor + version 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 DeployProcessorVersionRequest(proto.Message): + r"""Request message for the deploy processor version method. + + Attributes: + name (str): + Required. The processor version resource name + to be deployed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeployProcessorVersionResponse(proto.Message): + r"""Response message for the deploy processor version method. + """ + + +class DeployProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for deploy processor + version 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 UndeployProcessorVersionRequest(proto.Message): + r"""Request message for the undeploy processor version method. + + Attributes: + name (str): + Required. The processor version resource name + to be undeployed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeployProcessorVersionResponse(proto.Message): + r"""Response message for the undeploy processor version method. + """ + + +class UndeployProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for the undeploy + processor version 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 CreateProcessorRequest(proto.Message): + r"""Request message for create a processor. Notice this request + is sent to a regionalized backend service, and if the processor + type is not available on that region, the creation will fail. + + Attributes: + parent (str): + Required. The parent (project and location) under which to + create the processor. Format: + ``projects/{project}/locations/{location}`` + processor (google.cloud.documentai_v1beta3.types.Processor): + Required. The processor to be created, requires + [processor_type] and [display_name] to be set. Also, the + processor is under CMEK if CMEK fields are set. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + processor: gcd_processor.Processor = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_processor.Processor, + ) + + +class DeleteProcessorRequest(proto.Message): + r"""Request message for the delete processor method. + + Attributes: + name (str): + Required. The processor resource name to be + deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteProcessorMetadata(proto.Message): + r"""The long running operation metadata for delete processor + 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=5, + message=operation_metadata.CommonOperationMetadata, + ) + + +class EnableProcessorRequest(proto.Message): + r"""Request message for the enable processor method. + + Attributes: + name (str): + Required. The processor resource name to be + enabled. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EnableProcessorResponse(proto.Message): + r"""Response message for the enable processor method. + Intentionally empty proto for adding fields in future. + + """ + + +class EnableProcessorMetadata(proto.Message): + r"""The long running operation metadata for enable processor + 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=5, + message=operation_metadata.CommonOperationMetadata, + ) + + +class DisableProcessorRequest(proto.Message): + r"""Request message for the disable processor method. + + Attributes: + name (str): + Required. The processor resource name to be + disabled. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableProcessorResponse(proto.Message): + r"""Response message for the disable processor method. + Intentionally empty proto for adding fields in future. + + """ + + +class DisableProcessorMetadata(proto.Message): + r"""The long running operation metadata for disable processor + 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=5, + message=operation_metadata.CommonOperationMetadata, + ) + + +class SetDefaultProcessorVersionRequest(proto.Message): + r"""Request message for the set default processor version method. + + Attributes: + processor (str): + Required. The resource name of the + [Processor][google.cloud.documentai.v1beta3.Processor] to + change default version. + default_processor_version (str): + Required. The resource name of child + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to use as default. Format: + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{version}`` + """ + + processor: str = proto.Field( + proto.STRING, + number=1, + ) + default_processor_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SetDefaultProcessorVersionResponse(proto.Message): + r"""Response message for set default processor version method. + """ + + +class SetDefaultProcessorVersionMetadata(proto.Message): + r"""The long running operation metadata for set default processor + version 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 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. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_document (google.cloud.documentai_v1beta3.types.Document): + An inline document proto. + + This field is a member of `oneof`_ ``source``. + human_review_config (str): + Required. The resource name of the + HumanReviewConfig that the document will be + reviewed with. + document (google.cloud.documentai_v1beta3.types.Document): + The document that needs human review. + enable_schema_validation (bool): + Whether the validation should be performed on + the ad-hoc review request. + priority (google.cloud.documentai_v1beta3.types.ReviewDocumentRequest.Priority): + The priority of the human review task. + document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): + The document schema of the human review task. + """ + class Priority(proto.Enum): + r"""The priority level of the human review task. + + Values: + DEFAULT (0): + The default priority level. + URGENT (1): + The urgent priority level. The labeling + manager should allocate labeler resource to the + urgent task queue to respect this priority + level. + """ + DEFAULT = 0 + URGENT = 1 + + inline_document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + human_review_config: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + enable_schema_validation: bool = proto.Field( + proto.BOOL, + number=3, + ) + priority: Priority = proto.Field( + proto.ENUM, + number=5, + enum=Priority, + ) + document_schema: gcd_document_schema.DocumentSchema = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_document_schema.DocumentSchema, + ) + + +class ReviewDocumentResponse(proto.Message): + r"""Response message for review document method. + + Attributes: + gcs_destination (str): + The Cloud Storage uri for the human reviewed + document if the review is succeeded. + state (google.cloud.documentai_v1beta3.types.ReviewDocumentResponse.State): + The state of the review operation. + rejection_reason (str): + The reason why the review is rejected by + reviewer. + """ + class State(proto.Enum): + r"""Possible states of the review operation. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + REJECTED (1): + The review operation is rejected by the + reviewer. + SUCCEEDED (2): + The review operation is succeeded. + """ + STATE_UNSPECIFIED = 0 + REJECTED = 1 + SUCCEEDED = 2 + + gcs_destination: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + rejection_reason: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ReviewDocumentOperationMetadata(proto.Message): + r"""The long running operation metadata for review document + method. + + Attributes: + state (google.cloud.documentai_v1beta3.types.ReviewDocumentOperationMetadata.State): + Used only when Operation.done is false. + state_message (str): + A message providing more details about the + current state of processing. For example, the + error message if the operation is failed. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update time of the operation. + common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + question_id (str): + The Crowd Compute question ID. + """ + class State(proto.Enum): + r"""State of the longrunning operation. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + RUNNING (1): + Operation is still running. + CANCELLING (2): + Operation is being cancelled. + SUCCEEDED (3): + Operation succeeded. + FAILED (4): + Operation failed. + CANCELLED (5): + Operation is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + CANCELLING = 2 + SUCCEEDED = 3 + FAILED = 4 + CANCELLED = 5 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=operation_metadata.CommonOperationMetadata, + ) + question_id: str = proto.Field( + proto.STRING, + number=6, + ) + + +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/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py new file mode 100644 index 00000000..6b54cede --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py @@ -0,0 +1,242 @@ +# -*- 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 + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'DocumentSchema', + }, +) + + +class DocumentSchema(proto.Message): + r"""The schema defines the output of the processed document by a + processor. + + Attributes: + display_name (str): + Display name to show to users. + description (str): + Description of the schema. + entity_types (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType]): + Entity types of the schema. + metadata (google.cloud.documentai_v1beta3.types.DocumentSchema.Metadata): + Metadata of the schema. + """ + + class EntityType(proto.Message): + r"""EntityType is the wrapper of a label of the corresponding + model with detailed attributes and limitations for entity-based + processors. Multiple types can also compose a dependency tree to + represent nested types. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enum_values (google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.EnumValues): + If specified, lists all the possible values for this entity. + This should not be more than a handful of values. If the + number of values is >10 or could change frequently use the + ``EntityType.value_ontology`` field and specify a list of + all possible values in a value ontology file. + + This field is a member of `oneof`_ ``value_source``. + display_name (str): + User defined name for the type. + name (str): + Name of the type. It must be unique within the schema file + and cannot be a 'Common Type'. Besides that we use the + following naming conventions: + + - *use ``snake_casing``* + - name matching is case-sensitive + - 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 + compatibility. + base_types (MutableSequence[str]): + The entity type that this type is derived + from. For now, one and only one should be set. + properties (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.Property]): + Describing the nested structure, or + composition of an entity. + """ + + class EnumValues(proto.Message): + r"""Defines the a list of enum values. + + Attributes: + values (MutableSequence[str]): + The individual values that this enum values + type can include. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Property(proto.Message): + r"""Defines properties that can be part of the entity type. + + Attributes: + name (str): + The name of the property. Follows the same + guidelines as the EntityType name. + value_type (str): + A reference to the value type of the property. This type is + subject to the same conventions as the ``Entity.base_types`` + field. + occurrence_type (google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.Property.OccurrenceType): + Occurrence type limits the number of + instances an entity type appears in the + document. + """ + class OccurrenceType(proto.Enum): + r"""Types of occurrences of the entity type in the document. + Note: this represents the number of instances of an entity + types, not number of mentions of a given entity instance. + + Values: + OCCURRENCE_TYPE_UNSPECIFIED (0): + Unspecified occurrence type. + OPTIONAL_ONCE (1): + There will be zero or one instance of this + entity type. + OPTIONAL_MULTIPLE (2): + The entity type will appear zero or multiple + times. + REQUIRED_ONCE (3): + The entity type will only appear exactly + once. + REQUIRED_MULTIPLE (4): + The entity type will appear once or more + times. + """ + OCCURRENCE_TYPE_UNSPECIFIED = 0 + OPTIONAL_ONCE = 1 + OPTIONAL_MULTIPLE = 2 + REQUIRED_ONCE = 3 + REQUIRED_MULTIPLE = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value_type: str = proto.Field( + proto.STRING, + number=2, + ) + occurrence_type: 'DocumentSchema.EntityType.Property.OccurrenceType' = proto.Field( + proto.ENUM, + number=3, + enum='DocumentSchema.EntityType.Property.OccurrenceType', + ) + + enum_values: 'DocumentSchema.EntityType.EnumValues' = proto.Field( + proto.MESSAGE, + number=14, + oneof='value_source', + message='DocumentSchema.EntityType.EnumValues', + ) + display_name: str = proto.Field( + proto.STRING, + number=13, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + base_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + properties: MutableSequence['DocumentSchema.EntityType.Property'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='DocumentSchema.EntityType.Property', + ) + + class Metadata(proto.Message): + r"""Metadata for global schema behavior. + + Attributes: + document_splitter (bool): + If true, a ``document`` entity type can be applied to + subdocument ( splitting). Otherwise, it can only be applied + to the entire document (classification). + document_allow_multiple_labels (bool): + If true, on a given page, there can be multiple ``document`` + annotations covering it. + prefixed_naming_on_properties (bool): + If set, all the nested entities must be + prefixed with the parents. + skip_naming_validation (bool): + If set, we will skip the naming format validation in the + schema. So the string values in + ``DocumentSchema.EntityType.name`` and + ``DocumentSchema.EntityType.Property.name`` will not be + checked. + """ + + document_splitter: bool = proto.Field( + proto.BOOL, + number=1, + ) + document_allow_multiple_labels: bool = proto.Field( + proto.BOOL, + number=2, + ) + prefixed_naming_on_properties: bool = proto.Field( + proto.BOOL, + number=6, + ) + skip_naming_validation: bool = proto.Field( + proto.BOOL, + number=7, + ) + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + entity_types: MutableSequence[EntityType] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=EntityType, + ) + metadata: Metadata = proto.Field( + proto.MESSAGE, + number=4, + message=Metadata, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py new file mode 100644 index 00000000..6bb882c9 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py @@ -0,0 +1,342 @@ +# -*- 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 + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'EvaluationReference', + 'Evaluation', + }, +) + + +class EvaluationReference(proto.Message): + r"""Gives a short summary of an evaluation, and links to the + evaluation itself. + + Attributes: + operation (str): + The resource name of the Long Running + Operation for the evaluation. + evaluation (str): + The resource name of the evaluation. + aggregate_metrics (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): + An aggregate of the statistics for the + evaluation with fuzzy matching on. + aggregate_metrics_exact (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): + An aggregate of the statistics for the + evaluation with fuzzy matching off. + """ + + operation: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation: str = proto.Field( + proto.STRING, + number=2, + ) + aggregate_metrics: 'Evaluation.Metrics' = proto.Field( + proto.MESSAGE, + number=4, + message='Evaluation.Metrics', + ) + aggregate_metrics_exact: 'Evaluation.Metrics' = proto.Field( + proto.MESSAGE, + number=5, + message='Evaluation.Metrics', + ) + + +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. + + Values: + METRICS_TYPE_UNSPECIFIED (0): + The metrics type is unspecified. By default, + metrics without a particular specification are + for leaf entity types (i.e., top-level entity + types without child types, or child types which + are not parent types themselves). + AGGREGATE (1): + Indicates whether metrics for this particular + label type represent an aggregate of metrics for + other types instead of being based on actual + TP/FP/FN values for the label type. Metrics for + parent (i.e., non-leaf) entity types are an + aggregate of metrics for their children. + """ + 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/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py new file mode 100644 index 00000000..7f329da0 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py @@ -0,0 +1,99 @@ +# -*- 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 + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + }, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate (starts from the top of the + image). + """ + + x: int = proto.Field( + proto.INT32, + number=1, + ) + y: int = proto.Field( + proto.INT32, + number=2, + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate (starts from the top of the + image). + """ + + x: float = proto.Field( + proto.FLOAT, + number=1, + ) + y: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (MutableSequence[google.cloud.documentai_v1beta3.types.Vertex]): + The bounding polygon vertices. + normalized_vertices (MutableSequence[google.cloud.documentai_v1beta3.types.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices: MutableSequence['Vertex'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='NormalizedVertex', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py new file mode 100644 index 00000000..69e402a1 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py @@ -0,0 +1,96 @@ +# -*- 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 + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'CommonOperationMetadata', + }, +) + + +class CommonOperationMetadata(proto.Message): + r"""The common metadata for long running operations. + + Attributes: + state (google.cloud.documentai_v1beta3.types.CommonOperationMetadata.State): + The state of the operation. + state_message (str): + A message providing more details about the + current state of processing. + resource (str): + A related resource to this operation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update time of the operation. + """ + class State(proto.Enum): + r"""State of the longrunning operation. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + RUNNING (1): + Operation is still running. + CANCELLING (2): + Operation is being cancelled. + SUCCEEDED (3): + Operation succeeded. + FAILED (4): + Operation failed. + CANCELLED (5): + Operation is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + CANCELLING = 2 + SUCCEEDED = 3 + FAILED = 4 + CANCELLED = 5 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + resource: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py new file mode 100644 index 00000000..153bc8b5 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py @@ -0,0 +1,285 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.documentai_v1beta3.types import document_schema as gcd_document_schema +from google.cloud.documentai_v1beta3.types import evaluation +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'ProcessorVersion', + 'Processor', + }, +) + + +class ProcessorVersion(proto.Message): + r"""A processor version is an implementation of a processor. Each + processor can have multiple versions, pre-trained by Google + internally or up-trained by the customer. At a time, a processor + can only have one default version version. So the processor's + behavior (when processing documents) is defined by a default + version + + Attributes: + name (str): + The resource name of the processor version. Format: + ``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): + The time the processor version was created. + latest_evaluation (google.cloud.documentai_v1beta3.types.EvaluationReference): + The most recently invoked evaluation for the + processor version. + 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. + google_managed (bool): + Denotes that this ProcessorVersion is managed + by google. + deprecation_info (google.cloud.documentai_v1beta3.types.ProcessorVersion.DeprecationInfo): + If set, information about the eventual + deprecation of this version. + """ + class State(proto.Enum): + r"""The possible states of the processor version. + + Values: + STATE_UNSPECIFIED (0): + The processor version is in an unspecified + state. + DEPLOYED (1): + The processor version is deployed and can be + used for processing. + DEPLOYING (2): + The processor version is being deployed. + UNDEPLOYED (3): + The processor version is not deployed and + cannot be used for processing. + UNDEPLOYING (4): + The processor version is being undeployed. + CREATING (5): + The processor version is being created. + DELETING (6): + The processor version is being deleted. + FAILED (7): + The processor version failed and is in an + indeterminate state. + """ + STATE_UNSPECIFIED = 0 + DEPLOYED = 1 + DEPLOYING = 2 + UNDEPLOYED = 3 + UNDEPLOYING = 4 + CREATING = 5 + DELETING = 6 + FAILED = 7 + + class DeprecationInfo(proto.Message): + r"""Information about the upcoming deprecation of this processor + version. + + Attributes: + deprecation_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which this processor version will + be deprecated. + replacement_processor_version (str): + If set, the processor version that will be + used as a replacement. + """ + + deprecation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + replacement_processor_version: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + 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, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + latest_evaluation: evaluation.EvaluationReference = proto.Field( + proto.MESSAGE, + number=8, + message=evaluation.EvaluationReference, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=9, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=10, + ) + google_managed: bool = proto.Field( + proto.BOOL, + number=11, + ) + deprecation_info: DeprecationInfo = proto.Field( + proto.MESSAGE, + number=13, + message=DeprecationInfo, + ) + + +class Processor(proto.Message): + r"""The first-class citizen for Document AI. Each processor + defines how to extract structural information from a document. + + Attributes: + name (str): + Output only. Immutable. The resource name of the processor. + 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 + [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes]. + display_name (str): + The display name of the processor. + state (google.cloud.documentai_v1beta3.types.Processor.State): + Output only. The state of the processor. + default_processor_version (str): + The default processor version. + process_endpoint (str): + Output only. Immutable. The http endpoint + that can be called to invoke processing. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the processor was created. + kms_key_name (str): + The KMS key used for encryption/decryption in + CMEK scenarios. See + https://cloud.google.com/security-key-management. + """ + class State(proto.Enum): + r"""The possible states of the processor. + + Values: + STATE_UNSPECIFIED (0): + The processor is in an unspecified state. + ENABLED (1): + The processor is enabled, i.e., has an + enabled version which can currently serve + processing requests and all the feature + dependencies have been successfully initialized. + DISABLED (2): + The processor is disabled. + ENABLING (3): + The processor is being enabled, will become ``ENABLED`` if + successful. + DISABLING (4): + The processor is being disabled, will become ``DISABLED`` if + successful. + CREATING (5): + The processor is being created, will become either + ``ENABLED`` (for successful creation) or ``FAILED`` (for + failed ones). Once a processor is in this state, it can then + be used for document processing, but the feature + dependencies of the processor might not be fully created + yet. + FAILED (6): + The processor failed during creation or + initialization of feature dependencies. The user + should delete the processor and recreate one as + all the functionalities of the processor are + disabled. + DELETING (7): + The processor is being deleted, will be + removed if successful. + """ + STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + ENABLING = 3 + DISABLING = 4 + CREATING = 5 + FAILED = 6 + DELETING = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + default_processor_version: str = proto.Field( + proto.STRING, + number=9, + ) + process_endpoint: str = proto.Field( + proto.STRING, + number=6, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py new file mode 100644 index 00000000..79381f6b --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py @@ -0,0 +1,106 @@ +# -*- 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 + +import proto # type: ignore + +from google.api import launch_stage_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + manifest={ + 'ProcessorType', + }, +) + + +class ProcessorType(proto.Message): + r"""A processor type is responsible for performing a certain + document understanding task on a certain type of document. + + Attributes: + name (str): + The resource name of the processor type. Format: + ``projects/{project}/processorTypes/{processor_type}`` + type_ (str): + The processor type, e.g., ``OCR_PROCESSOR``, + ``INVOICE_PROCESSOR``, etc. + category (str): + The processor category, used by UI to group + processor types. + available_locations (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType.LocationInfo]): + The locations in which this processor is + available. + allow_creation (bool): + Whether the processor type allows creation. + If true, users can create a processor of this + processor type. Otherwise, users need to request + access. + launch_stage (google.api.launch_stage_pb2.LaunchStage): + Launch stage of the processor type + sample_document_uris (MutableSequence[str]): + A set of Cloud Storage URIs of sample + documents for this processor. + """ + + class LocationInfo(proto.Message): + r"""The location information about where the processor is + available. + + Attributes: + location_id (str): + The location id, currently must be one of [us, eu]. + """ + + location_id: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + category: str = proto.Field( + proto.STRING, + number=3, + ) + available_locations: MutableSequence[LocationInfo] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=LocationInfo, + ) + allow_creation: bool = proto.Field( + proto.BOOL, + number=6, + ) + launch_stage: launch_stage_pb2.LaunchStage = proto.Field( + proto.ENUM, + number=8, + enum=launch_stage_pb2.LaunchStage, + ) + sample_document_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/mypy.ini b/owl-bot-staging/v1beta3/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1beta3/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1beta3/noxfile.py b/owl-bot-staging/v1beta3/noxfile.py new file mode 100644 index 00000000..ef7ddc7a --- /dev/null +++ b/owl-bot-staging/v1beta3/noxfile.py @@ -0,0 +1,184 @@ +# -*- 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. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/documentai_v1beta3/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py new file mode 100644 index 00000000..9a52ef4a --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_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 BatchProcessDocuments +# 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_BatchProcessDocuments_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_batch_process_documents(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py new file mode 100644 index 00000000..25f76623 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_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 BatchProcessDocuments +# 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_BatchProcessDocuments_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_batch_process_documents(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.BatchProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.batch_process_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py new file mode 100644 index 00000000..8487077f --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_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 CreateProcessor +# 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_CreateProcessor_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_create_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py new file mode 100644 index 00000000..2705de55 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_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 CreateProcessor +# 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_CreateProcessor_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_create_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.CreateProcessorRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py new file mode 100644 index 00000000..54141136 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_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 DeleteProcessor +# 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_DeleteProcessor_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_delete_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py new file mode 100644 index 00000000..38e0353b --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_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 DeleteProcessor +# 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_DeleteProcessor_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_delete_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py new file mode 100644 index 00000000..16913bec --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_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 DeleteProcessorVersion +# 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_DeleteProcessorVersion_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_delete_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py new file mode 100644 index 00000000..d291a9ae --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_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 DeleteProcessorVersion +# 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_DeleteProcessorVersion_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_delete_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeleteProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py new file mode 100644 index 00000000..e5b67ec9 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_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 DeployProcessorVersion +# 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_DeployProcessorVersion_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_deploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py new file mode 100644 index 00000000..3ad835fe --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_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 DeployProcessorVersion +# 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_DeployProcessorVersion_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_deploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py new file mode 100644 index 00000000..2bc67064 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_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 DisableProcessor +# 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_DisableProcessor_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_disable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py new file mode 100644 index 00000000..4f3d70ab --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_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 DisableProcessor +# 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_DisableProcessor_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_disable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.DisableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py new file mode 100644 index 00000000..8d4dfd9e --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_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 EnableProcessor +# 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_EnableProcessor_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_enable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py new file mode 100644 index 00000000..98b1561f --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_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 EnableProcessor +# 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_EnableProcessor_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_enable_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EnableProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.enable_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py new file mode 100644 index 00000000..8290b418 --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py new file mode 100644 index 00000000..fb730993 --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py new file mode 100644 index 00000000..9c0ab5dd --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_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 FetchProcessorTypes +# 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_FetchProcessorTypes_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_fetch_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.fetch_processor_types(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py new file mode 100644 index 00000000..df7a7069 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_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 FetchProcessorTypes +# 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_FetchProcessorTypes_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_fetch_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.FetchProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + response = client.fetch_processor_types(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py new file mode 100644 index 00000000..c2306172 --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py new file mode 100644 index 00000000..d126b6bd --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py new file mode 100644 index 00000000..cc90dd2e --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_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 GetProcessor +# 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_GetProcessor_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_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py new file mode 100644 index 00000000..ebdf0676 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_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 GetProcessor +# 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_GetProcessor_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_processor(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py new file mode 100644 index 00000000..6f276a69 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_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 GetProcessorType +# 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_GetProcessorType_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_processor_type(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_type(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py new file mode 100644 index 00000000..1db0b26c --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_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 GetProcessorType +# 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_GetProcessorType_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_processor_type(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorTypeRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_type(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py new file mode 100644 index 00000000..27a73ebb --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_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 GetProcessorVersion +# 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_GetProcessorVersion_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_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor_version(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py new file mode 100644 index 00000000..d4a19a6d --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_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 GetProcessorVersion +# 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_GetProcessorVersion_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_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetProcessorVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor_version(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py new file mode 100644 index 00000000..be38a005 --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py new file mode 100644 index 00000000..3849d890 --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py new file mode 100644 index 00000000..9e42bdf3 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_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 ListProcessorTypes +# 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_ListProcessorTypes_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_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py new file mode 100644 index 00000000..ff735a06 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_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 ListProcessorTypes +# 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_ListProcessorTypes_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_processor_types(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorTypesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_types(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py new file mode 100644 index 00000000..6179291d --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_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 ListProcessorVersions +# 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_ListProcessorVersions_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_processor_versions(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py new file mode 100644 index 00000000..981de716 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_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 ListProcessorVersions +# 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_ListProcessorVersions_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_processor_versions(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processor_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py new file mode 100644 index 00000000..c9bb0a54 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_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 ListProcessors +# 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_ListProcessors_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_processors(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py new file mode 100644 index 00000000..2b853df9 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_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 ListProcessors +# 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_ListProcessors_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_processors(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py new file mode 100644 index 00000000..c9f2346e --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_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 ProcessDocument +# 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_ProcessDocument_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_process_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = await client.process_document(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py new file mode 100644 index 00000000..cfae6a5e --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_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 ProcessDocument +# 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_ProcessDocument_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_process_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ProcessRequest( + inline_document=inline_document, + name="name_value", + ) + + # Make the request + response = client.process_document(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py new file mode 100644 index 00000000..ddafdd90 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py @@ -0,0 +1,60 @@ +# -*- 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 ReviewDocument +# 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_ReviewDocument_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_review_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py new file mode 100644 index 00000000..66a9bec3 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py @@ -0,0 +1,60 @@ +# -*- 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 ReviewDocument +# 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_ReviewDocument_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_review_document(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + inline_document = documentai_v1beta3.Document() + inline_document.uri = "uri_value" + + request = documentai_v1beta3.ReviewDocumentRequest( + inline_document=inline_document, + human_review_config="human_review_config_value", + ) + + # Make the request + operation = client.review_document(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py new file mode 100644 index 00000000..bf49fea1 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py @@ -0,0 +1,57 @@ +# -*- 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 SetDefaultProcessorVersion +# 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_SetDefaultProcessorVersion_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_set_default_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py new file mode 100644 index 00000000..95b38d3b --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py @@ -0,0 +1,57 @@ +# -*- 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 SetDefaultProcessorVersion +# 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_SetDefaultProcessorVersion_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_set_default_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.SetDefaultProcessorVersionRequest( + processor="processor_value", + default_processor_version="default_processor_version_value", + ) + + # Make the request + operation = client.set_default_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py new file mode 100644 index 00000000..e1c21207 --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py new file mode 100644 index 00000000..3d9fa4ea --- /dev/null +++ b/owl-bot-staging/v1beta3/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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py new file mode 100644 index 00000000..fbbc23db --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_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 UndeployProcessorVersion +# 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_UndeployProcessorVersion_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_undeploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py new file mode 100644 index 00000000..eb761cb3 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_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 UndeployProcessorVersion +# 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_UndeployProcessorVersion_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_undeploy_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.UndeployProcessorVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json b/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json new file mode 100644 index 00000000..f02752f1 --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json @@ -0,0 +1,3549 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.documentai.v1beta3", + "version": "v1beta3" + } + ], + "language": "PYTHON", + "name": "google-cloud-documentai", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.batch_process_documents", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "BatchProcessDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.BatchProcessRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "batch_process_documents" + }, + "description": "Sample for BatchProcessDocuments", + "file": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_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_batch_process_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.batch_process_documents", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "BatchProcessDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.BatchProcessRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "batch_process_documents" + }, + "description": "Sample for BatchProcessDocuments", + "file": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_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_batch_process_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.create_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.documentai_v1beta3.types.Processor" + }, + { + "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.Processor", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_create_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_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_create_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.create_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.documentai_v1beta3.types.Processor" + }, + { + "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.Processor", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_create_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_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_create_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.delete_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_processor_version" + }, + "description": "Sample for DeleteProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_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_delete_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.delete_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_processor_version" + }, + "description": "Sample for DeleteProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_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_delete_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.delete_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_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_delete_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.delete_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_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_delete_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.deploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "deploy_processor_version" + }, + "description": "Sample for DeployProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_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_deploy_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.deploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "deploy_processor_version" + }, + "description": "Sample for DeployProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_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_deploy_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.disable_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DisableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DisableProcessorRequest" + }, + { + "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": "disable_processor" + }, + "description": "Sample for DisableProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_disable_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_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_disable_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.disable_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "DisableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.DisableProcessorRequest" + }, + { + "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": "disable_processor" + }, + "description": "Sample for DisableProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_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_disable_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.enable_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EnableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.EnableProcessorRequest" + }, + { + "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": "enable_processor" + }, + "description": "Sample for EnableProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_enable_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_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_enable_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.enable_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EnableProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.EnableProcessorRequest" + }, + { + "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": "enable_processor" + }, + "description": "Sample for EnableProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_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_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": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.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_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_type", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest" + }, + { + "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.ProcessorType", + "shortName": "get_processor_type" + }, + "description": "Sample for GetProcessorType", + "file": "documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_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_processor_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor_type", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest" + }, + { + "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.ProcessorType", + "shortName": "get_processor_type" + }, + "description": "Sample for GetProcessorType", + "file": "documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_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_processor_type_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_GetProcessorVersion_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_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.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_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_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_processor_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" + }, + { + "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.Processor", + "shortName": "get_processor" + }, + "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_GetProcessor_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_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" + }, + { + "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.Processor", + "shortName": "get_processor" + }, + "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_GetProcessor_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_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_evaluations", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" + }, + { + "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.services.document_processor_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" + }, + "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_ListEvaluations_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_evaluations", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" + }, + { + "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.services.document_processor_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" + }, + "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_ListEvaluations_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processor_types", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest" + }, + { + "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.services.document_processor_service.pagers.ListProcessorTypesAsyncPager", + "shortName": "list_processor_types" + }, + "description": "Sample for ListProcessorTypes", + "file": "documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processor_types", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest" + }, + { + "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.services.document_processor_service.pagers.ListProcessorTypesPager", + "shortName": "list_processor_types" + }, + "description": "Sample for ListProcessorTypes", + "file": "documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processor_versions", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest" + }, + { + "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.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager", + "shortName": "list_processor_versions" + }, + "description": "Sample for ListProcessorVersions", + "file": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processor_versions", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessorVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest" + }, + { + "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.services.document_processor_service.pagers.ListProcessorVersionsPager", + "shortName": "list_processor_versions" + }, + "description": "Sample for ListProcessorVersions", + "file": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processors", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListProcessorsRequest" + }, + { + "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.services.document_processor_service.pagers.ListProcessorsAsyncPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "documentai_v1beta3_generated_document_processor_service_list_processors_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_processors_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processors", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ListProcessorsRequest" + }, + { + "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.services.document_processor_service.pagers.ListProcessorsPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "documentai_v1beta3_generated_document_processor_service_list_processors_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_list_processors_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.process_document", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ProcessDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ProcessRequest" + }, + { + "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.ProcessResponse", + "shortName": "process_document" + }, + "description": "Sample for ProcessDocument", + "file": "documentai_v1beta3_generated_document_processor_service_process_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_process_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.process_document", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ProcessDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ProcessRequest" + }, + { + "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.ProcessResponse", + "shortName": "process_document" + }, + "description": "Sample for ProcessDocument", + "file": "documentai_v1beta3_generated_document_processor_service_process_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_process_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.review_document", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ReviewDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ReviewDocumentRequest" + }, + { + "name": "human_review_config", + "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": "review_document" + }, + "description": "Sample for ReviewDocument", + "file": "documentai_v1beta3_generated_document_processor_service_review_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_review_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.review_document", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "ReviewDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.ReviewDocumentRequest" + }, + { + "name": "human_review_config", + "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": "review_document" + }, + "description": "Sample for ReviewDocument", + "file": "documentai_v1beta3_generated_document_processor_service_review_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_review_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.set_default_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "SetDefaultProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest" + }, + { + "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": "set_default_processor_version" + }, + "description": "Sample for SetDefaultProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.set_default_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "SetDefaultProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest" + }, + { + "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": "set_default_processor_version" + }, + "description": "Sample for SetDefaultProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "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": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.undeploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "UndeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "undeploy_processor_version" + }, + "description": "Sample for UndeployProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_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_undeploy_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.undeploy_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "UndeployProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "undeploy_processor_version" + }, + "description": "Sample for UndeployProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_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_undeploy_processor_version_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py b/owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py new file mode 100644 index 00000000..75ec155f --- /dev/null +++ b/owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py @@ -0,0 +1,197 @@ +#! /usr/bin/env python3 +# -*- 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. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class documentaiCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_process_documents': ('name', 'input_configs', 'output_config', 'input_documents', 'document_output_config', 'skip_human_review', 'process_options', ), + 'create_processor': ('parent', 'processor', ), + 'delete_processor': ('name', ), + 'delete_processor_version': ('name', ), + '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_type': ('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', 'process_options', ), + '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', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=documentaiCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the documentai client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta3/setup.py b/owl-bot-staging/v1beta3/setup.py new file mode 100644 index 00000000..3b12ce4b --- /dev/null +++ b/owl-bot-staging/v1beta3/setup.py @@ -0,0 +1,90 @@ +# -*- 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. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-documentai' + + +description = "Google Cloud Documentai API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-documentai" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.10.txt b/owl-bot-staging/v1beta3/testing/constraints-3.10.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta3/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.11.txt b/owl-bot-staging/v1beta3/testing/constraints-3.11.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta3/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.12.txt b/owl-bot-staging/v1beta3/testing/constraints-3.12.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta3/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.7.txt b/owl-bot-staging/v1beta3/testing/constraints-3.7.txt new file mode 100644 index 00000000..6c44adfe --- /dev/null +++ b/owl-bot-staging/v1beta3/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.8.txt b/owl-bot-staging/v1beta3/testing/constraints-3.8.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta3/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.9.txt b/owl-bot-staging/v1beta3/testing/constraints-3.9.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta3/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta3/tests/__init__.py b/owl-bot-staging/v1beta3/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta3/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta3/tests/unit/__init__.py b/owl-bot-staging/v1beta3/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta3/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py b/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py b/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py new file mode 100644 index 00000000..d50c24f1 --- /dev/null +++ b/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py @@ -0,0 +1,13258 @@ +# -*- 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. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.documentai_v1beta3.services.document_processor_service import DocumentProcessorServiceAsyncClient +from google.cloud.documentai_v1beta3.services.document_processor_service import DocumentProcessorServiceClient +from google.cloud.documentai_v1beta3.services.document_processor_service import pagers +from google.cloud.documentai_v1beta3.services.document_processor_service import transports +from google.cloud.documentai_v1beta3.types import barcode +from google.cloud.documentai_v1beta3.types import document +from google.cloud.documentai_v1beta3.types import document_io +from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import document_schema +from google.cloud.documentai_v1beta3.types import evaluation +from google.cloud.documentai_v1beta3.types import geometry +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 +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from google.type import money_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(None) is None + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentProcessorServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentProcessorServiceClient, "grpc"), + (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), + (DocumentProcessorServiceClient, "rest"), +]) +def test_document_processor_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'documentai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://documentai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DocumentProcessorServiceRestTransport, "rest"), +]) +def test_document_processor_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentProcessorServiceClient, "grpc"), + (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), + (DocumentProcessorServiceClient, "rest"), +]) +def test_document_processor_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'documentai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://documentai.googleapis.com' + ) + + +def test_document_processor_service_client_get_transport_class(): + transport = DocumentProcessorServiceClient.get_transport_class() + available_transports = [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceRestTransport, + ] + assert transport in available_transports + + transport = DocumentProcessorServiceClient.get_transport_class("grpc") + assert transport == transports.DocumentProcessorServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), +]) +@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) +@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) +def test_document_processor_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "true"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "false"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "true"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) +@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_document_processor_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DocumentProcessorServiceClient, DocumentProcessorServiceAsyncClient +]) +@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) +@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) +def test_document_processor_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), +]) +def test_document_processor_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", None), +]) +def test_document_processor_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_document_processor_service_client_client_options_from_dict(): + with mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentProcessorServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_document_processor_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "documentai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="documentai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ProcessRequest, + dict, +]) +def test_process_document(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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ProcessResponse( + human_review_operation='human_review_operation_value', + ) + response = client.process_document(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.ProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.ProcessResponse) + assert response.human_review_operation == 'human_review_operation_value' + + +def test_process_document_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.process_document), + '__call__') as call: + client.process_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ProcessRequest() + +@pytest.mark.asyncio +async def test_process_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ProcessRequest): + 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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse( + human_review_operation='human_review_operation_value', + )) + response = await client.process_document(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.ProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.ProcessResponse) + assert response.human_review_operation == 'human_review_operation_value' + + +@pytest.mark.asyncio +async def test_process_document_async_from_dict(): + await test_process_document_async(request_type=dict) + + +def test_process_document_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.ProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.process_document), + '__call__') as call: + call.return_value = document_processor_service.ProcessResponse() + client.process_document(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_process_document_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.ProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.process_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) + await client.process_document(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_process_document_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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ProcessResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.process_document( + 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_process_document_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.process_document( + document_processor_service.ProcessRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_process_document_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.process_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ProcessResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.process_document( + 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_process_document_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.process_document( + document_processor_service.ProcessRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.BatchProcessRequest, + dict, +]) +def test_batch_process_documents(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.batch_process_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_process_documents(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.BatchProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_process_documents_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.batch_process_documents), + '__call__') as call: + client.batch_process_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.BatchProcessRequest() + +@pytest.mark.asyncio +async def test_batch_process_documents_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.BatchProcessRequest): + 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.batch_process_documents), + '__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.batch_process_documents(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.BatchProcessRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_process_documents_async_from_dict(): + await test_batch_process_documents_async(request_type=dict) + + +def test_batch_process_documents_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.BatchProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_process_documents(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_batch_process_documents_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.BatchProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_process_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_process_documents(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_batch_process_documents_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.batch_process_documents), + '__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.batch_process_documents( + 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_batch_process_documents_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.batch_process_documents( + document_processor_service.BatchProcessRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_batch_process_documents_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.batch_process_documents), + '__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.batch_process_documents( + 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_batch_process_documents_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.batch_process_documents( + document_processor_service.BatchProcessRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.FetchProcessorTypesRequest, + dict, +]) +def test_fetch_processor_types(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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.FetchProcessorTypesResponse( + ) + response = client.fetch_processor_types(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.FetchProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) + + +def test_fetch_processor_types_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.fetch_processor_types), + '__call__') as call: + client.fetch_processor_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.FetchProcessorTypesRequest() + +@pytest.mark.asyncio +async def test_fetch_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.FetchProcessorTypesRequest): + 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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse( + )) + response = await client.fetch_processor_types(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.FetchProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) + + +@pytest.mark.asyncio +async def test_fetch_processor_types_async_from_dict(): + await test_fetch_processor_types_async(request_type=dict) + + +def test_fetch_processor_types_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.FetchProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_processor_types), + '__call__') as call: + call.return_value = document_processor_service.FetchProcessorTypesResponse() + client.fetch_processor_types(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_fetch_processor_types_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.FetchProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_processor_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) + await client.fetch_processor_types(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_fetch_processor_types_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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.FetchProcessorTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_processor_types( + 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_fetch_processor_types_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.fetch_processor_types( + document_processor_service.FetchProcessorTypesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_fetch_processor_types_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.fetch_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.FetchProcessorTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_processor_types( + 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_fetch_processor_types_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.fetch_processor_types( + document_processor_service.FetchProcessorTypesRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorTypesRequest, + dict, +]) +def test_list_processor_types(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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorTypesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_processor_types(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.ListProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_types_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_processor_types), + '__call__') as call: + client.list_processor_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListProcessorTypesRequest() + +@pytest.mark.asyncio +async def test_list_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorTypesRequest): + 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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_processor_types(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.ListProcessorTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorTypesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_processor_types_async_from_dict(): + await test_list_processor_types_async(request_type=dict) + + +def test_list_processor_types_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.ListProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_types), + '__call__') as call: + call.return_value = document_processor_service.ListProcessorTypesResponse() + client.list_processor_types(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_processor_types_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.ListProcessorTypesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) + await client.list_processor_types(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_processor_types_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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processor_types( + 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_processor_types_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_processor_types( + document_processor_service.ListProcessorTypesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processor_types_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_processor_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processor_types( + 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_processor_types_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_processor_types( + document_processor_service.ListProcessorTypesRequest(), + parent='parent_value', + ) + + +def test_list_processor_types_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_processor_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processor_types(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor_type.ProcessorType) + for i in results) +def test_list_processor_types_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_processor_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processor_types(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_processor_types_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_processor_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processor_types(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, processor_type.ProcessorType) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processor_types_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_processor_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_processor_types(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 + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorTypeRequest, + dict, +]) +def test_get_processor_type(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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor_type.ProcessorType( + name='name_value', + type_='type__value', + category='category_value', + allow_creation=True, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + sample_document_uris=['sample_document_uris_value'], + ) + response = client.get_processor_type(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.GetProcessorTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor_type.ProcessorType) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.category == 'category_value' + assert response.allow_creation is True + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.sample_document_uris == ['sample_document_uris_value'] + + +def test_get_processor_type_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_processor_type), + '__call__') as call: + client.get_processor_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetProcessorTypeRequest() + +@pytest.mark.asyncio +async def test_get_processor_type_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorTypeRequest): + 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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType( + name='name_value', + type_='type__value', + category='category_value', + allow_creation=True, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + sample_document_uris=['sample_document_uris_value'], + )) + response = await client.get_processor_type(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.GetProcessorTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor_type.ProcessorType) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.category == 'category_value' + assert response.allow_creation is True + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.sample_document_uris == ['sample_document_uris_value'] + + +@pytest.mark.asyncio +async def test_get_processor_type_async_from_dict(): + await test_get_processor_type_async(request_type=dict) + + +def test_get_processor_type_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.GetProcessorTypeRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_type), + '__call__') as call: + call.return_value = processor_type.ProcessorType() + client.get_processor_type(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_processor_type_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.GetProcessorTypeRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) + await client.get_processor_type(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_processor_type_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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor_type.ProcessorType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor_type( + 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_processor_type_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_processor_type( + document_processor_service.GetProcessorTypeRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_processor_type_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_processor_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor_type.ProcessorType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor_type( + 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_processor_type_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_processor_type( + document_processor_service.GetProcessorTypeRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorsRequest, + dict, +]) +def test_list_processors(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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_processors(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.ListProcessorsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processors_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_processors), + '__call__') as call: + client.list_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListProcessorsRequest() + +@pytest.mark.asyncio +async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorsRequest): + 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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_processors(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.ListProcessorsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_processors_async_from_dict(): + await test_list_processors_async(request_type=dict) + + +def test_list_processors_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.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = document_processor_service.ListProcessorsResponse() + client.list_processors(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_processors_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.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) + await client.list_processors(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_processors_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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processors( + 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_processors_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_processors( + document_processor_service.ListProcessorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processors_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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processors( + 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_processors_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_processors( + document_processor_service.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_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_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processors(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.Processor) + for i in results) +def test_list_processors_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_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processors(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_processors_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_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processors(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, processor.Processor) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processors_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_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_processors(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 + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorRequest, + dict, +]) +def test_get_processor(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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + response = client.get_processor(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.GetProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_get_processor_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_processor), + '__call__') as call: + client.get_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetProcessorRequest() + +@pytest.mark.asyncio +async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorRequest): + 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + )) + response = await client.get_processor(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.GetProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +@pytest.mark.asyncio +async def test_get_processor_async_from_dict(): + await test_get_processor_async(request_type=dict) + + +def test_get_processor_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.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = processor.Processor() + client.get_processor(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_processor_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.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) + await client.get_processor(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_processor_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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.Processor() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor( + 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_processor_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_processor( + document_processor_service.GetProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_processor_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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.Processor() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor( + 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_processor_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_processor( + document_processor_service.GetProcessorRequest(), + name='name_value', + ) + + +@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", [ + document_processor_service.GetProcessorVersionRequest, + dict, +]) +def test_get_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.get_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.ProcessorVersion( + name='name_value', + display_name='display_name_value', + state=processor.ProcessorVersion.State.DEPLOYED, + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + google_managed=True, + ) + response = client.get_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.GetProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.ProcessorVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == processor.ProcessorVersion.State.DEPLOYED + assert response.kms_key_name == 'kms_key_name_value' + assert response.kms_key_version_name == 'kms_key_version_name_value' + assert response.google_managed is True + + +def test_get_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.get_processor_version), + '__call__') as call: + client.get_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_get_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorVersionRequest): + 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_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion( + name='name_value', + display_name='display_name_value', + state=processor.ProcessorVersion.State.DEPLOYED, + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + google_managed=True, + )) + response = await client.get_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.GetProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.ProcessorVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == processor.ProcessorVersion.State.DEPLOYED + assert response.kms_key_name == 'kms_key_name_value' + assert response.kms_key_version_name == 'kms_key_version_name_value' + assert response.google_managed is True + + +@pytest.mark.asyncio +async def test_get_processor_version_async_from_dict(): + await test_get_processor_version_async(request_type=dict) + + +def test_get_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.GetProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_version), + '__call__') as call: + call.return_value = processor.ProcessorVersion() + client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_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.GetProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) + await client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_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.get_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.ProcessorVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor_version( + 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_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.get_processor_version( + document_processor_service.GetProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_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.get_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = processor.ProcessorVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor_version( + 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_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.get_processor_version( + document_processor_service.GetProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorVersionsRequest, + dict, +]) +def test_list_processor_versions(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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_processor_versions(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.ListProcessorVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_versions_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_processor_versions), + '__call__') as call: + client.list_processor_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListProcessorVersionsRequest() + +@pytest.mark.asyncio +async def test_list_processor_versions_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorVersionsRequest): + 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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_processor_versions(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.ListProcessorVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_processor_versions_async_from_dict(): + await test_list_processor_versions_async(request_type=dict) + + +def test_list_processor_versions_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.ListProcessorVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_versions), + '__call__') as call: + call.return_value = document_processor_service.ListProcessorVersionsResponse() + client.list_processor_versions(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_processor_versions_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.ListProcessorVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processor_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) + await client.list_processor_versions(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_processor_versions_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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processor_versions( + 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_processor_versions_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_processor_versions( + document_processor_service.ListProcessorVersionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processor_versions_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_processor_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListProcessorVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processor_versions( + 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_processor_versions_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_processor_versions( + document_processor_service.ListProcessorVersionsRequest(), + parent='parent_value', + ) + + +def test_list_processor_versions_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_processor_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processor_versions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.ProcessorVersion) + for i in results) +def test_list_processor_versions_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_processor_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processor_versions(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_processor_versions_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_processor_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processor_versions(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, processor.ProcessorVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processor_versions_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_processor_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_processor_versions(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 + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorVersionRequest, + dict, +]) +def test_delete_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.delete_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_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.DeleteProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_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.delete_processor_version), + '__call__') as call: + client.delete_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DeleteProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_delete_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorVersionRequest): + 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.delete_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.delete_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.DeleteProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_processor_version_async_from_dict(): + await test_delete_processor_version_async(request_type=dict) + + +def test_delete_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.DeleteProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_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.DeleteProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_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.delete_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.delete_processor_version( + 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_delete_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.delete_processor_version( + document_processor_service.DeleteProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_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.delete_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.delete_processor_version( + 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_delete_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.delete_processor_version( + document_processor_service.DeleteProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeployProcessorVersionRequest, + dict, +]) +def test_deploy_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.deploy_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.deploy_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.DeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_deploy_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.deploy_processor_version), + '__call__') as call: + client.deploy_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DeployProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_deploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeployProcessorVersionRequest): + 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.deploy_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.deploy_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.DeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_deploy_processor_version_async_from_dict(): + await test_deploy_processor_version_async(request_type=dict) + + +def test_deploy_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.DeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.deploy_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_deploy_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.DeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.deploy_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_deploy_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.deploy_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.deploy_processor_version( + 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_deploy_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.deploy_processor_version( + document_processor_service.DeployProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_deploy_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.deploy_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.deploy_processor_version( + 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_deploy_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.deploy_processor_version( + document_processor_service.DeployProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.UndeployProcessorVersionRequest, + dict, +]) +def test_undeploy_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.undeploy_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.undeploy_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.UndeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_undeploy_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.undeploy_processor_version), + '__call__') as call: + client.undeploy_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.UndeployProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_undeploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.UndeployProcessorVersionRequest): + 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.undeploy_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.undeploy_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.UndeployProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_undeploy_processor_version_async_from_dict(): + await test_undeploy_processor_version_async(request_type=dict) + + +def test_undeploy_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.UndeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.undeploy_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_undeploy_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.UndeployProcessorVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.undeploy_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_undeploy_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.undeploy_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.undeploy_processor_version( + 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_undeploy_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.undeploy_processor_version( + document_processor_service.UndeployProcessorVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_undeploy_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.undeploy_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.undeploy_processor_version( + 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_undeploy_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.undeploy_processor_version( + document_processor_service.UndeployProcessorVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.CreateProcessorRequest, + dict, +]) +def test_create_processor(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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=gcd_processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + response = client.create_processor(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.CreateProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == gcd_processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_create_processor_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.create_processor), + '__call__') as call: + client.create_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.CreateProcessorRequest() + +@pytest.mark.asyncio +async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.CreateProcessorRequest): + 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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=gcd_processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + )) + response = await client.create_processor(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.CreateProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == gcd_processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +@pytest.mark.asyncio +async def test_create_processor_async_from_dict(): + await test_create_processor_async(request_type=dict) + + +def test_create_processor_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.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = gcd_processor.Processor() + client.create_processor(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_create_processor_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.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) + await client.create_processor(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_create_processor_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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_processor.Processor() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_processor( + parent='parent_value', + processor=gcd_processor.Processor(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 + mock_val = gcd_processor.Processor(name='name_value') + assert arg == mock_val + + +def test_create_processor_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.create_processor( + document_processor_service.CreateProcessorRequest(), + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_processor_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.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_processor.Processor() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_processor( + parent='parent_value', + processor=gcd_processor.Processor(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 + mock_val = gcd_processor.Processor(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_processor_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.create_processor( + document_processor_service.CreateProcessorRequest(), + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorRequest, + dict, +]) +def test_delete_processor(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.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_processor(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.DeleteProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_processor_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.delete_processor), + '__call__') as call: + client.delete_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DeleteProcessorRequest() + +@pytest.mark.asyncio +async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorRequest): + 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.delete_processor), + '__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.delete_processor(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.DeleteProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_processor_async_from_dict(): + await test_delete_processor_async(request_type=dict) + + +def test_delete_processor_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.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_processor(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_delete_processor_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.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_processor(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_delete_processor_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.delete_processor), + '__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.delete_processor( + 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_delete_processor_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.delete_processor( + document_processor_service.DeleteProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_processor_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.delete_processor), + '__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.delete_processor( + 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_delete_processor_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.delete_processor( + document_processor_service.DeleteProcessorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.EnableProcessorRequest, + dict, +]) +def test_enable_processor(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.enable_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.enable_processor(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.EnableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_enable_processor_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.enable_processor), + '__call__') as call: + client.enable_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.EnableProcessorRequest() + +@pytest.mark.asyncio +async def test_enable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EnableProcessorRequest): + 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.enable_processor), + '__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.enable_processor(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.EnableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_enable_processor_async_from_dict(): + await test_enable_processor_async(request_type=dict) + + +def test_enable_processor_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.EnableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.enable_processor(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_enable_processor_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.EnableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.enable_processor(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'] + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DisableProcessorRequest, + dict, +]) +def test_disable_processor(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.disable_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.disable_processor(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.DisableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_disable_processor_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.disable_processor), + '__call__') as call: + client.disable_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.DisableProcessorRequest() + +@pytest.mark.asyncio +async def test_disable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DisableProcessorRequest): + 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.disable_processor), + '__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.disable_processor(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.DisableProcessorRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_disable_processor_async_from_dict(): + await test_disable_processor_async(request_type=dict) + + +def test_disable_processor_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.DisableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.disable_processor(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_disable_processor_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.DisableProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.disable_processor(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'] + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.SetDefaultProcessorVersionRequest, + dict, +]) +def test_set_default_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.set_default_processor_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_default_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.SetDefaultProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_default_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.set_default_processor_version), + '__call__') as call: + client.set_default_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() + +@pytest.mark.asyncio +async def test_set_default_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.SetDefaultProcessorVersionRequest): + 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.set_default_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.set_default_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.SetDefaultProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_default_processor_version_async_from_dict(): + await test_set_default_processor_version_async(request_type=dict) + + +def test_set_default_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.SetDefaultProcessorVersionRequest() + + request.processor = 'processor_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_processor_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_default_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=processor_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_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.SetDefaultProcessorVersionRequest() + + request.processor = 'processor_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_processor_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_default_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=processor_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ReviewDocumentRequest, + dict, +]) +def test_review_document(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.review_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.review_document(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.ReviewDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_review_document_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.review_document), + '__call__') as call: + client.review_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ReviewDocumentRequest() + +@pytest.mark.asyncio +async def test_review_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ReviewDocumentRequest): + 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.review_document), + '__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.review_document(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.ReviewDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_review_document_async_from_dict(): + await test_review_document_async(request_type=dict) + + +def test_review_document_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.ReviewDocumentRequest() + + request.human_review_config = 'human_review_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.review_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.review_document(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', + 'human_review_config=human_review_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_review_document_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.ReviewDocumentRequest() + + request.human_review_config = 'human_review_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.review_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.review_document(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', + 'human_review_config=human_review_config_value', + ) in kw['metadata'] + + +def test_review_document_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.review_document), + '__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.review_document( + human_review_config='human_review_config_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].human_review_config + mock_val = 'human_review_config_value' + assert arg == mock_val + + +def test_review_document_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.review_document( + document_processor_service.ReviewDocumentRequest(), + human_review_config='human_review_config_value', + ) + +@pytest.mark.asyncio +async def test_review_document_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.review_document), + '__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.review_document( + human_review_config='human_review_config_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].human_review_config + mock_val = 'human_review_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_review_document_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.review_document( + document_processor_service.ReviewDocumentRequest(), + human_review_config='human_review_config_value', + ) + + +@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, + ) + + # 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 = 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', + ) + + # 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 + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ProcessRequest, + dict, +]) +def test_process_document_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse( + human_review_operation='human_review_operation_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.process_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.ProcessResponse) + assert response.human_review_operation == 'human_review_operation_value' + + +def test_process_document_rest_required_fields(request_type=document_processor_service.ProcessRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.process_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_process_document_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.process_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_process_document_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_process_document") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_process_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ProcessRequest.pb(document_processor_service.ProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ProcessResponse.to_json(document_processor_service.ProcessResponse()) + + request = document_processor_service.ProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ProcessResponse() + + client.process_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_process_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ProcessRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.process_document(request) + + +def test_process_document_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.process_document(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}:process" % client.transport._host, args[1]) + + +def test_process_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.process_document( + document_processor_service.ProcessRequest(), + name='name_value', + ) + + +def test_process_document_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.BatchProcessRequest, + dict, +]) +def test_batch_process_documents_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_process_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_process_documents_rest_required_fields(request_type=document_processor_service.BatchProcessRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_process_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_process_documents_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_process_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_process_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_batch_process_documents") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_batch_process_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.BatchProcessRequest.pb(document_processor_service.BatchProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.BatchProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_process_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_process_documents_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.BatchProcessRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_process_documents(request) + + +def test_batch_process_documents_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.batch_process_documents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}:batchProcess" % client.transport._host, args[1]) + + +def test_batch_process_documents_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_process_documents( + document_processor_service.BatchProcessRequest(), + name='name_value', + ) + + +def test_batch_process_documents_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.FetchProcessorTypesRequest, + dict, +]) +def test_fetch_processor_types_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.fetch_processor_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) + + +def test_fetch_processor_types_rest_required_fields(request_type=document_processor_service.FetchProcessorTypesRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.fetch_processor_types(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_processor_types_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_processor_types_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.FetchProcessorTypesRequest.pb(document_processor_service.FetchProcessorTypesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.FetchProcessorTypesResponse.to_json(document_processor_service.FetchProcessorTypesResponse()) + + request = document_processor_service.FetchProcessorTypesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.FetchProcessorTypesResponse() + + client.fetch_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.FetchProcessorTypesRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_processor_types(request) + + +def test_fetch_processor_types_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.fetch_processor_types(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}:fetchProcessorTypes" % client.transport._host, args[1]) + + +def test_fetch_processor_types_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_processor_types( + document_processor_service.FetchProcessorTypesRequest(), + parent='parent_value', + ) + + +def test_fetch_processor_types_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorTypesRequest, + dict, +]) +def test_list_processor_types_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processor_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_types_rest_required_fields(request_type=document_processor_service.ListProcessorTypesRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processor_types(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processor_types_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processor_types._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processor_types_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListProcessorTypesRequest.pb(document_processor_service.ListProcessorTypesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListProcessorTypesResponse.to_json(document_processor_service.ListProcessorTypesResponse()) + + request = document_processor_service.ListProcessorTypesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListProcessorTypesResponse() + + client.list_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorTypesRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processor_types(request) + + +def test_list_processor_types_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processor_types(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processorTypes" % client.transport._host, args[1]) + + +def test_list_processor_types_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processor_types( + document_processor_service.ListProcessorTypesRequest(), + parent='parent_value', + ) + + +def test_list_processor_types_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token='def', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListProcessorTypesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_processor_types(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor_type.ProcessorType) + for i in results) + + pages = list(client.list_processor_types(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorTypeRequest, + dict, +]) +def test_get_processor_type_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor_type.ProcessorType( + name='name_value', + type_='type__value', + category='category_value', + allow_creation=True, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + sample_document_uris=['sample_document_uris_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor_type.ProcessorType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, processor_type.ProcessorType) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.category == 'category_value' + assert response.allow_creation is True + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.sample_document_uris == ['sample_document_uris_value'] + + +def test_get_processor_type_rest_required_fields(request_type=document_processor_service.GetProcessorTypeRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = processor_type.ProcessorType() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = processor_type.ProcessorType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor_type(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_type_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor_type._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_type_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetProcessorTypeRequest.pb(document_processor_service.GetProcessorTypeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = processor_type.ProcessorType.to_json(processor_type.ProcessorType()) + + request = document_processor_service.GetProcessorTypeRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = processor_type.ProcessorType() + + client.get_processor_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_type_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorTypeRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor_type(request) + + +def test_get_processor_type_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor_type.ProcessorType() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor_type.ProcessorType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor_type(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processorTypes/*}" % client.transport._host, args[1]) + + +def test_get_processor_type_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor_type( + document_processor_service.GetProcessorTypeRequest(), + name='name_value', + ) + + +def test_get_processor_type_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorsRequest, + dict, +]) +def test_list_processors_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processors_rest_required_fields(request_type=document_processor_service.ListProcessorsRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processors(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processors_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processors._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processors_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processors") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListProcessorsRequest.pb(document_processor_service.ListProcessorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListProcessorsResponse.to_json(document_processor_service.ListProcessorsResponse()) + + request = document_processor_service.ListProcessorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListProcessorsResponse() + + client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processors(request) + + +def test_list_processors_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processors(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_list_processors_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processors( + document_processor_service.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListProcessorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_processors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.Processor) + for i in results) + + pages = list(client.list_processors(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorRequest, + dict, +]) +def test_get_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_get_processor_rest_required_fields(request_type=document_processor_service.GetProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = processor.Processor() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetProcessorRequest.pb(document_processor_service.GetProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = processor.Processor.to_json(processor.Processor()) + + request = document_processor_service.GetProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = processor.Processor() + + client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor(request) + + +def test_get_processor_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.Processor() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_get_processor_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor( + document_processor_service.GetProcessorRequest(), + name='name_value', + ) + + +def test_get_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.TrainProcessorVersionRequest, + dict, +]) +def test_train_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.train_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_train_processor_version_rest_required_fields(request_type=document_processor_service.TrainProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.train_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_train_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.train_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "processorVersion", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_train_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_train_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_train_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.TrainProcessorVersionRequest.pb(document_processor_service.TrainProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.TrainProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.train_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_train_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.TrainProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.train_processor_version(request) + + +def test_train_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + processor_version=processor.ProcessorVersion(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.train_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:train" % client.transport._host, args[1]) + + +def test_train_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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'), + ) + + +def test_train_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetProcessorVersionRequest, + dict, +]) +def test_get_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.ProcessorVersion( + name='name_value', + display_name='display_name_value', + state=processor.ProcessorVersion.State.DEPLOYED, + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + google_managed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.ProcessorVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, processor.ProcessorVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == processor.ProcessorVersion.State.DEPLOYED + assert response.kms_key_name == 'kms_key_name_value' + assert response.kms_key_version_name == 'kms_key_version_name_value' + assert response.google_managed is True + + +def test_get_processor_version_rest_required_fields(request_type=document_processor_service.GetProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = processor.ProcessorVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = processor.ProcessorVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetProcessorVersionRequest.pb(document_processor_service.GetProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = processor.ProcessorVersion.to_json(processor.ProcessorVersion()) + + request = document_processor_service.GetProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = processor.ProcessorVersion() + + client.get_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor_version(request) + + +def test_get_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = processor.ProcessorVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor.ProcessorVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) + + +def test_get_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor_version( + document_processor_service.GetProcessorVersionRequest(), + name='name_value', + ) + + +def test_get_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListProcessorVersionsRequest, + dict, +]) +def test_list_processor_versions_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorVersionsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processor_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_processor_versions_rest_required_fields(request_type=document_processor_service.ListProcessorVersionsRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processor_versions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processor_versions_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processor_versions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processor_versions_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_versions") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListProcessorVersionsRequest.pb(document_processor_service.ListProcessorVersionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListProcessorVersionsResponse.to_json(document_processor_service.ListProcessorVersionsResponse()) + + request = document_processor_service.ListProcessorVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListProcessorVersionsResponse() + + client.list_processor_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processor_versions_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorVersionsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processor_versions(request) + + +def test_list_processor_versions_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processor_versions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions" % client.transport._host, args[1]) + + +def test_list_processor_versions_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processor_versions( + document_processor_service.ListProcessorVersionsRequest(), + parent='parent_value', + ) + + +def test_list_processor_versions_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + next_page_token='abc', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], + next_page_token='def', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + ], + next_page_token='ghi', + ), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListProcessorVersionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} + + pager = client.list_processor_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.ProcessorVersion) + for i in results) + + pages = list(client.list_processor_versions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorVersionRequest, + dict, +]) +def test_delete_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_processor_version_rest_required_fields(request_type=document_processor_service.DeleteProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DeleteProcessorVersionRequest.pb(document_processor_service.DeleteProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DeleteProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_processor_version(request) + + +def test_delete_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) + + +def test_delete_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_processor_version( + document_processor_service.DeleteProcessorVersionRequest(), + name='name_value', + ) + + +def test_delete_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeployProcessorVersionRequest, + dict, +]) +def test_deploy_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.deploy_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_deploy_processor_version_rest_required_fields(request_type=document_processor_service.DeployProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.deploy_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_deploy_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_deploy_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_deploy_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_deploy_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DeployProcessorVersionRequest.pb(document_processor_service.DeployProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DeployProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.deploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_deploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeployProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.deploy_processor_version(request) + + +def test_deploy_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.deploy_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" % client.transport._host, args[1]) + + +def test_deploy_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.deploy_processor_version( + document_processor_service.DeployProcessorVersionRequest(), + name='name_value', + ) + + +def test_deploy_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.UndeployProcessorVersionRequest, + dict, +]) +def test_undeploy_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.undeploy_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undeploy_processor_version_rest_required_fields(request_type=document_processor_service.UndeployProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.undeploy_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undeploy_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undeploy_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_undeploy_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_undeploy_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.UndeployProcessorVersionRequest.pb(document_processor_service.UndeployProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.UndeployProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undeploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undeploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.UndeployProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undeploy_processor_version(request) + + +def test_undeploy_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.undeploy_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" % client.transport._host, args[1]) + + +def test_undeploy_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undeploy_processor_version( + document_processor_service.UndeployProcessorVersionRequest(), + name='name_value', + ) + + +def test_undeploy_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.CreateProcessorRequest, + dict, +]) +def test_create_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_processor.Processor( + name='name_value', + type_='type__value', + display_name='display_name_value', + state=gcd_processor.Processor.State.ENABLED, + default_processor_version='default_processor_version_value', + process_endpoint='process_endpoint_value', + kms_key_name='kms_key_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_processor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_processor.Processor) + assert response.name == 'name_value' + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.state == gcd_processor.Processor.State.ENABLED + assert response.default_processor_version == 'default_processor_version_value' + assert response.process_endpoint == 'process_endpoint_value' + assert response.kms_key_name == 'kms_key_name_value' + + +def test_create_processor_rest_required_fields(request_type=document_processor_service.CreateProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_processor.Processor() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "processor", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_create_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.CreateProcessorRequest.pb(document_processor_service.CreateProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_processor.Processor.to_json(gcd_processor.Processor()) + + request = document_processor_service.CreateProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_processor.Processor() + + client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.CreateProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_processor(request) + + +def test_create_processor_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_processor.Processor() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_create_processor_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_processor( + document_processor_service.CreateProcessorRequest(), + parent='parent_value', + processor=gcd_processor.Processor(name='name_value'), + ) + + +def test_create_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DeleteProcessorRequest, + dict, +]) +def test_delete_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_processor_rest_required_fields(request_type=document_processor_service.DeleteProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DeleteProcessorRequest.pb(document_processor_service.DeleteProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DeleteProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_processor(request) + + +def test_delete_processor_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_delete_processor_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_processor( + document_processor_service.DeleteProcessorRequest(), + name='name_value', + ) + + +def test_delete_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.EnableProcessorRequest, + dict, +]) +def test_enable_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.enable_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_enable_processor_rest_required_fields(request_type=document_processor_service.EnableProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.enable_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_enable_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.enable_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enable_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.EnableProcessorRequest.pb(document_processor_service.EnableProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.EnableProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.enable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_enable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EnableProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.enable_processor(request) + + +def test_enable_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.DisableProcessorRequest, + dict, +]) +def test_disable_processor_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.disable_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_disable_processor_rest_required_fields(request_type=document_processor_service.DisableProcessorRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.disable_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_disable_processor_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.disable_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_processor_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.DisableProcessorRequest.pb(document_processor_service.DisableProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.DisableProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.disable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_disable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DisableProcessorRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.disable_processor(request) + + +def test_disable_processor_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.SetDefaultProcessorVersionRequest, + dict, +]) +def test_set_default_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_default_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_set_default_processor_version_rest_required_fields(request_type=document_processor_service.SetDefaultProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["processor"] = "" + request_init["default_processor_version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["processor"] = 'processor_value' + jsonified_request["defaultProcessorVersion"] = 'default_processor_version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "processor" in jsonified_request + assert jsonified_request["processor"] == 'processor_value' + assert "defaultProcessorVersion" in jsonified_request + assert jsonified_request["defaultProcessorVersion"] == 'default_processor_version_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_default_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_default_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_default_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("processor", "defaultProcessorVersion", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_default_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_set_default_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_set_default_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb(document_processor_service.SetDefaultProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.SetDefaultProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.set_default_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_default_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.SetDefaultProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_default_processor_version(request) + + +def test_set_default_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ReviewDocumentRequest, + dict, +]) +def test_review_document_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.review_document(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_review_document_rest_required_fields(request_type=document_processor_service.ReviewDocumentRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["human_review_config"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["humanReviewConfig"] = 'human_review_config_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "humanReviewConfig" in jsonified_request + assert jsonified_request["humanReviewConfig"] == 'human_review_config_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.review_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_review_document_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.review_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("humanReviewConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_review_document_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_review_document") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_review_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ReviewDocumentRequest.pb(document_processor_service.ReviewDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.ReviewDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.review_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_review_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ReviewDocumentRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.review_document(request) + + +def test_review_document_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} + + # get truthy value for each flattened field + mock_args = dict( + human_review_config='human_review_config_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.review_document(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" % client.transport._host, args[1]) + + +def test_review_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.review_document( + document_processor_service.ReviewDocumentRequest(), + human_review_config='human_review_config_value', + ) + + +def test_review_document_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.EvaluateProcessorVersionRequest, + dict, +]) +def test_evaluate_processor_version_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.evaluate_processor_version(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_evaluate_processor_version_rest_required_fields(request_type=document_processor_service.EvaluateProcessorVersionRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["processor_version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["processorVersion"] = 'processor_version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "processorVersion" in jsonified_request + assert jsonified_request["processorVersion"] == 'processor_version_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.evaluate_processor_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_evaluate_processor_version_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.evaluate_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("processorVersion", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_evaluate_processor_version_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_evaluate_processor_version") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_evaluate_processor_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.EvaluateProcessorVersionRequest.pb(document_processor_service.EvaluateProcessorVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = document_processor_service.EvaluateProcessorVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.evaluate_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_evaluate_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EvaluateProcessorVersionRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.evaluate_processor_version(request) + + +def test_evaluate_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + processor_version='processor_version_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.evaluate_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion" % client.transport._host, args[1]) + + +def test_evaluate_processor_version_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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', + ) + + +def test_evaluate_processor_version_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.GetEvaluationRequest, + dict, +]) +def test_get_evaluation_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation( + name='name_value', + kms_key_name='kms_key_name_value', + kms_key_version_name='kms_key_version_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_evaluation(request) + + # 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_rest_required_fields(request_type=document_processor_service.GetEvaluationRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_evaluation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_evaluation_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_evaluation") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_evaluation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.GetEvaluationRequest.pb(document_processor_service.GetEvaluationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = evaluation.Evaluation.to_json(evaluation.Evaluation()) + + request = document_processor_service.GetEvaluationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.Evaluation() + + client.get_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_evaluation_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetEvaluationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_evaluation(request) + + +def test_get_evaluation_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}" % client.transport._host, args[1]) + + +def test_get_evaluation_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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', + ) + + +def test_get_evaluation_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_processor_service.ListEvaluationsRequest, + dict, +]) +def test_list_evaluations_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListEvaluationsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_evaluations(request) + + # 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_rest_required_fields(request_type=document_processor_service.ListEvaluationsRequest): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListEvaluationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_evaluations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_evaluations_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluations_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_evaluations") as post, \ + mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_evaluations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListEvaluationsRequest.pb(document_processor_service.ListEvaluationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ListEvaluationsResponse.to_json(document_processor_service.ListEvaluationsResponse()) + + request = document_processor_service.ListEvaluationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListEvaluationsResponse() + + client.list_evaluations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_evaluations_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListEvaluationsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_evaluations(request) + + +def test_list_evaluations_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListEvaluationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_evaluations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations" % client.transport._host, args[1]) + + +def test_list_evaluations_rest_flattened_error(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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', + ) + + +def test_list_evaluations_rest_pager(transport: str = 'rest'): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + 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(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_processor_service.ListEvaluationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} + + pager = client.list_evaluations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) + for i in results) + + pages = list(client.list_evaluations(request=sample_request).pages) + 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( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentProcessorServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentProcessorServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentProcessorServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceGrpcAsyncIOTransport, + transports.DocumentProcessorServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DocumentProcessorServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentProcessorServiceGrpcTransport, + ) + +def test_document_processor_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentProcessorServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_document_processor_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentProcessorServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'process_document', + 'batch_process_documents', + 'fetch_processor_types', + 'list_processor_types', + 'get_processor_type', + 'list_processors', + 'get_processor', + 'train_processor_version', + 'get_processor_version', + 'list_processor_versions', + 'delete_processor_version', + 'deploy_processor_version', + 'undeploy_processor_version', + 'create_processor', + 'delete_processor', + 'enable_processor', + 'disable_processor', + 'set_default_processor_version', + 'review_document', + 'evaluate_processor_version', + 'get_evaluation', + 'list_evaluations', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_document_processor_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentProcessorServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_document_processor_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentProcessorServiceTransport() + adc.assert_called_once() + + +def test_document_processor_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentProcessorServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceGrpcAsyncIOTransport, + ], +) +def test_document_processor_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentProcessorServiceGrpcTransport, + transports.DocumentProcessorServiceGrpcAsyncIOTransport, + transports.DocumentProcessorServiceRestTransport, + ], +) +def test_document_processor_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentProcessorServiceGrpcTransport, grpc_helpers), + (transports.DocumentProcessorServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_document_processor_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "documentai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="documentai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) +def test_document_processor_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_document_processor_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.DocumentProcessorServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_document_processor_service_rest_lro_client(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_processor_service_host_no_port(transport_name): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'documentai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://documentai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_processor_service_host_with_port(transport_name): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'documentai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://documentai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_document_processor_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DocumentProcessorServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DocumentProcessorServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.process_document._session + session2 = client2.transport.process_document._session + assert session1 != session2 + session1 = client1.transport.batch_process_documents._session + session2 = client2.transport.batch_process_documents._session + assert session1 != session2 + session1 = client1.transport.fetch_processor_types._session + session2 = client2.transport.fetch_processor_types._session + assert session1 != session2 + session1 = client1.transport.list_processor_types._session + session2 = client2.transport.list_processor_types._session + assert session1 != session2 + session1 = client1.transport.get_processor_type._session + session2 = client2.transport.get_processor_type._session + assert session1 != session2 + session1 = client1.transport.list_processors._session + session2 = client2.transport.list_processors._session + assert session1 != session2 + session1 = client1.transport.get_processor._session + session2 = client2.transport.get_processor._session + assert session1 != session2 + session1 = client1.transport.train_processor_version._session + session2 = client2.transport.train_processor_version._session + assert session1 != session2 + session1 = client1.transport.get_processor_version._session + session2 = client2.transport.get_processor_version._session + assert session1 != session2 + session1 = client1.transport.list_processor_versions._session + session2 = client2.transport.list_processor_versions._session + assert session1 != session2 + session1 = client1.transport.delete_processor_version._session + session2 = client2.transport.delete_processor_version._session + assert session1 != session2 + session1 = client1.transport.deploy_processor_version._session + session2 = client2.transport.deploy_processor_version._session + assert session1 != session2 + session1 = client1.transport.undeploy_processor_version._session + session2 = client2.transport.undeploy_processor_version._session + assert session1 != session2 + session1 = client1.transport.create_processor._session + session2 = client2.transport.create_processor._session + assert session1 != session2 + session1 = client1.transport.delete_processor._session + session2 = client2.transport.delete_processor._session + assert session1 != session2 + session1 = client1.transport.enable_processor._session + session2 = client2.transport.enable_processor._session + assert session1 != session2 + session1 = client1.transport.disable_processor._session + session2 = client2.transport.disable_processor._session + assert session1 != session2 + session1 = client1.transport.set_default_processor_version._session + session2 = client2.transport.set_default_processor_version._session + assert session1 != session2 + session1 = client1.transport.review_document._session + session2 = client2.transport.review_document._session + assert session1 != session2 + session1 = client1.transport.evaluate_processor_version._session + session2 = client2.transport.evaluate_processor_version._session + assert session1 != session2 + session1 = client1.transport.get_evaluation._session + session2 = client2.transport.get_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_evaluations._session + session2 = client2.transport.list_evaluations._session + assert session1 != session2 +def test_document_processor_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentProcessorServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_document_processor_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) +def test_document_processor_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) +def test_document_processor_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_document_processor_service_grpc_lro_client(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_document_processor_service_grpc_lro_async_client(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +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, processor=processor, ) + actual = DocumentProcessorServiceClient.human_review_config_path(project, location, processor) + assert expected == actual + + +def test_parse_human_review_config_path(): + expected = { + "project": "clam", + "location": "whelk", + "processor": "octopus", + } + path = DocumentProcessorServiceClient.human_review_config_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_human_review_config_path(path) + assert expected == actual + +def test_processor_path(): + project = "oyster" + location = "nudibranch" + processor = "cuttlefish" + expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + actual = DocumentProcessorServiceClient.processor_path(project, location, processor) + assert expected == actual + + +def test_parse_processor_path(): + expected = { + "project": "mussel", + "location": "winkle", + "processor": "nautilus", + } + path = DocumentProcessorServiceClient.processor_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_processor_path(path) + assert expected == actual + +def test_processor_type_path(): + project = "scallop" + location = "abalone" + processor_type = "squid" + expected = "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) + actual = DocumentProcessorServiceClient.processor_type_path(project, location, processor_type) + assert expected == actual + + +def test_parse_processor_type_path(): + expected = { + "project": "clam", + "location": "whelk", + "processor_type": "octopus", + } + path = DocumentProcessorServiceClient.processor_type_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_processor_type_path(path) + assert expected == actual + +def test_processor_version_path(): + project = "oyster" + location = "nudibranch" + processor = "cuttlefish" + processor_version = "mussel" + expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) + actual = DocumentProcessorServiceClient.processor_version_path(project, location, processor, processor_version) + assert expected == actual + + +def test_parse_processor_version_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "processor": "scallop", + "processor_version": "abalone", + } + path = DocumentProcessorServiceClient.processor_version_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_processor_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentProcessorServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DocumentProcessorServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentProcessorServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DocumentProcessorServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentProcessorServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DocumentProcessorServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DocumentProcessorServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DocumentProcessorServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DocumentProcessorServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DocumentProcessorServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentProcessorServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_cancel_operation(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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(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 response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(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 response is the type that we expect. + assert response is None + +def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(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=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + 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.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + 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_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_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_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(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=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + 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_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_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_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(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 response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + 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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(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 response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(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=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + 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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(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 response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + 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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(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 response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(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=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(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=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + 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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_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_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport), + (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 0a95dc6ce75d96723699edc545f56169851146b3 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 21 Feb 2023 20:14:45 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- google/cloud/documentai/__init__.py | 21 + google/cloud/documentai_v1/__init__.py | 21 + .../cloud/documentai_v1/gapic_metadata.json | 60 + .../async_client.py | 484 + .../document_processor_service/client.py | 514 + .../document_processor_service/pagers.py | 133 + .../transports/base.py | 61 +- .../transports/grpc.py | 120 +- .../transports/grpc_asyncio.py | 121 +- .../transports/rest.py | 562 +- google/cloud/documentai_v1/types/__init__.py | 21 + google/cloud/documentai_v1/types/document.py | 31 +- .../types/document_processor_service.py | 300 + .../documentai_v1/types/document_schema.py | 20 +- .../cloud/documentai_v1/types/evaluation.py | 39 +- google/cloud/documentai_v1/types/processor.py | 9 + owl-bot-staging/v1/.coveragerc | 13 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 - .../document_processor_service.rst | 10 - .../v1/docs/documentai_v1/services.rst | 6 - .../v1/docs/documentai_v1/types.rst | 6 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/cloud/documentai/__init__.py | 161 - .../google/cloud/documentai/gapic_version.py | 16 - .../v1/google/cloud/documentai/py.typed | 2 - .../v1/google/cloud/documentai_v1/__init__.py | 162 - .../cloud/documentai_v1/gapic_metadata.json | 358 - .../cloud/documentai_v1/gapic_version.py | 16 - .../v1/google/cloud/documentai_v1/py.typed | 2 - .../cloud/documentai_v1/services/__init__.py | 15 - .../document_processor_service/__init__.py | 22 - .../async_client.py | 2979 ---- .../document_processor_service/client.py | 3196 ---- .../document_processor_service/pagers.py | 505 - .../transports/__init__.py | 38 - .../transports/base.py | 519 - .../transports/grpc.py | 945 -- .../transports/grpc_asyncio.py | 944 -- .../transports/rest.py | 3288 ---- .../cloud/documentai_v1/types/__init__.py | 172 - .../cloud/documentai_v1/types/barcode.py | 85 - .../cloud/documentai_v1/types/document.py | 1708 -- .../cloud/documentai_v1/types/document_io.py | 221 - .../types/document_processor_service.py | 1361 -- .../documentai_v1/types/document_schema.py | 250 - .../cloud/documentai_v1/types/geometry.py | 99 - .../documentai_v1/types/operation_metadata.py | 96 - .../cloud/documentai_v1/types/processor.py | 285 - .../documentai_v1/types/processor_type.py | 106 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 184 - ...r_service_batch_process_documents_async.py | 56 - ...or_service_batch_process_documents_sync.py | 56 - ...rocessor_service_create_processor_async.py | 52 - ...processor_service_create_processor_sync.py | 52 - ...rocessor_service_delete_processor_async.py | 56 - ...processor_service_delete_processor_sync.py | 56 - ..._service_delete_processor_version_async.py | 56 - ...r_service_delete_processor_version_sync.py | 56 - ..._service_deploy_processor_version_async.py | 56 - ...r_service_deploy_processor_version_sync.py | 56 - ...ocessor_service_disable_processor_async.py | 56 - ...rocessor_service_disable_processor_sync.py | 56 - ...rocessor_service_enable_processor_async.py | 56 - ...processor_service_enable_processor_sync.py | 56 - ...sor_service_fetch_processor_types_async.py | 52 - ...ssor_service_fetch_processor_types_sync.py | 52 - ...t_processor_service_get_processor_async.py | 52 - ...nt_processor_service_get_processor_sync.py | 52 - ...cessor_service_get_processor_type_async.py | 52 - ...ocessor_service_get_processor_type_sync.py | 52 - ...sor_service_get_processor_version_async.py | 52 - ...ssor_service_get_processor_version_sync.py | 52 - ...ssor_service_list_processor_types_async.py | 53 - ...essor_service_list_processor_types_sync.py | 53 - ...r_service_list_processor_versions_async.py | 53 - ...or_service_list_processor_versions_sync.py | 53 - ...processor_service_list_processors_async.py | 53 - ..._processor_service_list_processors_sync.py | 53 - ...rocessor_service_process_document_async.py | 56 - ...processor_service_process_document_sync.py | 56 - ...processor_service_review_document_async.py | 60 - ..._processor_service_review_document_sync.py | 60 - ...ice_set_default_processor_version_async.py | 57 - ...vice_set_default_processor_version_sync.py | 57 - ...ervice_undeploy_processor_version_async.py | 56 - ...service_undeploy_processor_version_sync.py | 56 - ...t_metadata_google.cloud.documentai.v1.json | 3549 ----- .../scripts/fixup_documentai_v1_keywords.py | 197 - owl-bot-staging/v1/setup.py | 91 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/documentai_v1/__init__.py | 16 - .../test_document_processor_service.py | 13252 --------------- owl-bot-staging/v1beta2/.coveragerc | 13 - owl-bot-staging/v1beta2/.flake8 | 33 - owl-bot-staging/v1beta2/MANIFEST.in | 2 - owl-bot-staging/v1beta2/README.rst | 49 - owl-bot-staging/v1beta2/docs/conf.py | 376 - .../document_understanding_service.rst | 6 - .../docs/documentai_v1beta2/services.rst | 6 - .../v1beta2/docs/documentai_v1beta2/types.rst | 6 - owl-bot-staging/v1beta2/docs/index.rst | 7 - .../google/cloud/documentai/__init__.py | 67 - .../google/cloud/documentai/gapic_version.py | 16 - .../v1beta2/google/cloud/documentai/py.typed | 2 - .../cloud/documentai_v1beta2/__init__.py | 68 - .../documentai_v1beta2/gapic_metadata.json | 43 - .../cloud/documentai_v1beta2/gapic_version.py | 16 - .../google/cloud/documentai_v1beta2/py.typed | 2 - .../documentai_v1beta2/services/__init__.py | 15 - .../__init__.py | 22 - .../async_client.py | 426 - .../document_understanding_service/client.py | 606 - .../transports/__init__.py | 33 - .../transports/base.py | 184 - .../transports/grpc.py | 313 - .../transports/grpc_asyncio.py | 312 - .../documentai_v1beta2/types/__init__.py | 64 - .../documentai_v1beta2/types/document.py | 1080 -- .../types/document_understanding.py | 591 - .../documentai_v1beta2/types/geometry.py | 97 - owl-bot-staging/v1beta2/mypy.ini | 3 - owl-bot-staging/v1beta2/noxfile.py | 184 - ...g_service_batch_process_documents_async.py | 60 - ...ng_service_batch_process_documents_sync.py | 60 - ...standing_service_process_document_async.py | 56 - ...rstanding_service_process_document_sync.py | 56 - ...adata_google.cloud.documentai.v1beta2.json | 329 - .../fixup_documentai_v1beta2_keywords.py | 177 - owl-bot-staging/v1beta2/setup.py | 90 - .../v1beta2/testing/constraints-3.10.txt | 6 - .../v1beta2/testing/constraints-3.11.txt | 6 - .../v1beta2/testing/constraints-3.12.txt | 6 - .../v1beta2/testing/constraints-3.7.txt | 9 - .../v1beta2/testing/constraints-3.8.txt | 6 - .../v1beta2/testing/constraints-3.9.txt | 6 - owl-bot-staging/v1beta2/tests/__init__.py | 16 - .../v1beta2/tests/unit/__init__.py | 16 - .../v1beta2/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/documentai_v1beta2/__init__.py | 16 - .../test_document_understanding_service.py | 1570 -- owl-bot-staging/v1beta3/.coveragerc | 13 - owl-bot-staging/v1beta3/.flake8 | 33 - owl-bot-staging/v1beta3/MANIFEST.in | 2 - owl-bot-staging/v1beta3/README.rst | 49 - owl-bot-staging/v1beta3/docs/conf.py | 376 - .../document_processor_service.rst | 10 - .../docs/documentai_v1beta3/services.rst | 6 - .../v1beta3/docs/documentai_v1beta3/types.rst | 6 - owl-bot-staging/v1beta3/docs/index.rst | 7 - .../google/cloud/documentai/__init__.py | 165 - .../google/cloud/documentai/gapic_version.py | 16 - .../v1beta3/google/cloud/documentai/py.typed | 2 - .../cloud/documentai_v1beta3/__init__.py | 166 - .../documentai_v1beta3/gapic_metadata.json | 358 - .../cloud/documentai_v1beta3/gapic_version.py | 16 - .../google/cloud/documentai_v1beta3/py.typed | 2 - .../documentai_v1beta3/services/__init__.py | 15 - .../document_processor_service/__init__.py | 22 - .../async_client.py | 2981 ---- .../document_processor_service/client.py | 3198 ---- .../document_processor_service/pagers.py | 505 - .../transports/__init__.py | 38 - .../transports/base.py | 519 - .../transports/grpc.py | 945 -- .../transports/grpc_asyncio.py | 944 -- .../transports/rest.py | 3280 ---- .../documentai_v1beta3/types/__init__.py | 176 - .../cloud/documentai_v1beta3/types/barcode.py | 85 - .../documentai_v1beta3/types/document.py | 1712 -- .../documentai_v1beta3/types/document_io.py | 245 - .../types/document_processor_service.py | 1534 -- .../types/document_schema.py | 242 - .../documentai_v1beta3/types/evaluation.py | 342 - .../documentai_v1beta3/types/geometry.py | 99 - .../types/operation_metadata.py | 96 - .../documentai_v1beta3/types/processor.py | 285 - .../types/processor_type.py | 106 - owl-bot-staging/v1beta3/mypy.ini | 3 - owl-bot-staging/v1beta3/noxfile.py | 184 - ...r_service_batch_process_documents_async.py | 56 - ...or_service_batch_process_documents_sync.py | 56 - ...rocessor_service_create_processor_async.py | 52 - ...processor_service_create_processor_sync.py | 52 - ...rocessor_service_delete_processor_async.py | 56 - ...processor_service_delete_processor_sync.py | 56 - ..._service_delete_processor_version_async.py | 56 - ...r_service_delete_processor_version_sync.py | 56 - ..._service_deploy_processor_version_async.py | 56 - ...r_service_deploy_processor_version_sync.py | 56 - ...ocessor_service_disable_processor_async.py | 56 - ...rocessor_service_disable_processor_sync.py | 56 - ...rocessor_service_enable_processor_async.py | 56 - ...processor_service_enable_processor_sync.py | 56 - ...ervice_evaluate_processor_version_async.py | 56 - ...service_evaluate_processor_version_sync.py | 56 - ...sor_service_fetch_processor_types_async.py | 52 - ...ssor_service_fetch_processor_types_sync.py | 52 - ..._processor_service_get_evaluation_async.py | 52 - ...t_processor_service_get_evaluation_sync.py | 52 - ...t_processor_service_get_processor_async.py | 52 - ...nt_processor_service_get_processor_sync.py | 52 - ...cessor_service_get_processor_type_async.py | 52 - ...ocessor_service_get_processor_type_sync.py | 52 - ...sor_service_get_processor_version_async.py | 52 - ...ssor_service_get_processor_version_sync.py | 52 - ...rocessor_service_list_evaluations_async.py | 53 - ...processor_service_list_evaluations_sync.py | 53 - ...ssor_service_list_processor_types_async.py | 53 - ...essor_service_list_processor_types_sync.py | 53 - ...r_service_list_processor_versions_async.py | 53 - ...or_service_list_processor_versions_sync.py | 53 - ...processor_service_list_processors_async.py | 53 - ..._processor_service_list_processors_sync.py | 53 - ...rocessor_service_process_document_async.py | 56 - ...processor_service_process_document_sync.py | 56 - ...processor_service_review_document_async.py | 60 - ..._processor_service_review_document_sync.py | 60 - ...ice_set_default_processor_version_async.py | 57 - ...vice_set_default_processor_version_sync.py | 57 - ...r_service_train_processor_version_async.py | 56 - ...or_service_train_processor_version_sync.py | 56 - ...ervice_undeploy_processor_version_async.py | 56 - ...service_undeploy_processor_version_sync.py | 56 - ...adata_google.cloud.documentai.v1beta3.json | 3549 ----- .../fixup_documentai_v1beta3_keywords.py | 197 - owl-bot-staging/v1beta3/setup.py | 90 - .../v1beta3/testing/constraints-3.10.txt | 6 - .../v1beta3/testing/constraints-3.11.txt | 6 - .../v1beta3/testing/constraints-3.12.txt | 6 - .../v1beta3/testing/constraints-3.7.txt | 9 - .../v1beta3/testing/constraints-3.8.txt | 6 - .../v1beta3/testing/constraints-3.9.txt | 6 - owl-bot-staging/v1beta3/tests/__init__.py | 16 - .../v1beta3/tests/unit/__init__.py | 16 - .../v1beta3/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/documentai_v1beta3/__init__.py | 16 - .../test_document_processor_service.py | 13258 ---------------- ...ervice_evaluate_processor_version_async.py | 0 ...service_evaluate_processor_version_sync.py | 0 ..._processor_service_get_evaluation_async.py | 0 ...t_processor_service_get_evaluation_sync.py | 0 ...rocessor_service_list_evaluations_async.py | 0 ...processor_service_list_evaluations_sync.py | 0 ...r_service_train_processor_version_async.py | 0 ...or_service_train_processor_version_sync.py | 0 ...t_metadata_google.cloud.documentai.v1.json | 782 +- ...adata_google.cloud.documentai.v1beta2.json | 2 +- ...adata_google.cloud.documentai.v1beta3.json | 2 +- scripts/fixup_documentai_v1_keywords.py | 4 + .../test_document_processor_service.py | 4984 ++++-- 262 files changed, 6892 insertions(+), 84330 deletions(-) rename {owl-bot-staging/v1/google => google}/cloud/documentai_v1/types/evaluation.py (92%) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst delete mode 100644 owl-bot-staging/v1/docs/documentai_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/documentai_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/documentai/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py delete mode 100644 owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py delete mode 100644 owl-bot-staging/v1beta2/.coveragerc delete mode 100644 owl-bot-staging/v1beta2/.flake8 delete mode 100644 owl-bot-staging/v1beta2/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta2/README.rst delete mode 100644 owl-bot-staging/v1beta2/docs/conf.py delete mode 100644 owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst delete mode 100644 owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst delete mode 100644 owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst delete mode 100644 owl-bot-staging/v1beta2/docs/index.rst delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai/py.typed delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py delete mode 100644 owl-bot-staging/v1beta2/mypy.ini delete mode 100644 owl-bot-staging/v1beta2/noxfile.py delete mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py delete mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py delete mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py delete mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py delete mode 100644 owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json delete mode 100644 owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py delete mode 100644 owl-bot-staging/v1beta2/setup.py delete mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1beta2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1beta2/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py delete mode 100644 owl-bot-staging/v1beta3/.coveragerc delete mode 100644 owl-bot-staging/v1beta3/.flake8 delete mode 100644 owl-bot-staging/v1beta3/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta3/README.rst delete mode 100644 owl-bot-staging/v1beta3/docs/conf.py delete mode 100644 owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst delete mode 100644 owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst delete mode 100644 owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst delete mode 100644 owl-bot-staging/v1beta3/docs/index.rst delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai/py.typed delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py delete mode 100644 owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py delete mode 100644 owl-bot-staging/v1beta3/mypy.ini delete mode 100644 owl-bot-staging/v1beta3/noxfile.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py delete mode 100644 owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json delete mode 100644 owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py delete mode 100644 owl-bot-staging/v1beta3/setup.py delete mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1beta3/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1beta3/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta3/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py delete mode 100644 owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py (100%) diff --git a/google/cloud/documentai/__init__.py b/google/cloud/documentai/__init__.py index 29407c4c..fcc932dc 100644 --- a/google/cloud/documentai/__init__.py +++ b/google/cloud/documentai/__init__.py @@ -52,12 +52,18 @@ EnableProcessorMetadata, EnableProcessorRequest, EnableProcessorResponse, + EvaluateProcessorVersionMetadata, + EvaluateProcessorVersionRequest, + EvaluateProcessorVersionResponse, FetchProcessorTypesRequest, FetchProcessorTypesResponse, + GetEvaluationRequest, GetProcessorRequest, GetProcessorTypeRequest, GetProcessorVersionRequest, HumanReviewStatus, + ListEvaluationsRequest, + ListEvaluationsResponse, ListProcessorsRequest, ListProcessorsResponse, ListProcessorTypesRequest, @@ -72,11 +78,15 @@ SetDefaultProcessorVersionMetadata, SetDefaultProcessorVersionRequest, SetDefaultProcessorVersionResponse, + TrainProcessorVersionMetadata, + TrainProcessorVersionRequest, + TrainProcessorVersionResponse, UndeployProcessorVersionMetadata, UndeployProcessorVersionRequest, UndeployProcessorVersionResponse, ) from google.cloud.documentai_v1.types.document_schema import DocumentSchema +from google.cloud.documentai_v1.types.evaluation import Evaluation, EvaluationReference from google.cloud.documentai_v1.types.geometry import ( BoundingPoly, NormalizedVertex, @@ -114,12 +124,18 @@ "EnableProcessorMetadata", "EnableProcessorRequest", "EnableProcessorResponse", + "EvaluateProcessorVersionMetadata", + "EvaluateProcessorVersionRequest", + "EvaluateProcessorVersionResponse", "FetchProcessorTypesRequest", "FetchProcessorTypesResponse", + "GetEvaluationRequest", "GetProcessorRequest", "GetProcessorTypeRequest", "GetProcessorVersionRequest", "HumanReviewStatus", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "ListProcessorsRequest", "ListProcessorsResponse", "ListProcessorTypesRequest", @@ -134,10 +150,15 @@ "SetDefaultProcessorVersionMetadata", "SetDefaultProcessorVersionRequest", "SetDefaultProcessorVersionResponse", + "TrainProcessorVersionMetadata", + "TrainProcessorVersionRequest", + "TrainProcessorVersionResponse", "UndeployProcessorVersionMetadata", "UndeployProcessorVersionRequest", "UndeployProcessorVersionResponse", "DocumentSchema", + "Evaluation", + "EvaluationReference", "BoundingPoly", "NormalizedVertex", "Vertex", diff --git a/google/cloud/documentai_v1/__init__.py b/google/cloud/documentai_v1/__init__.py index de139074..dc26842d 100644 --- a/google/cloud/documentai_v1/__init__.py +++ b/google/cloud/documentai_v1/__init__.py @@ -50,12 +50,18 @@ EnableProcessorMetadata, EnableProcessorRequest, EnableProcessorResponse, + EvaluateProcessorVersionMetadata, + EvaluateProcessorVersionRequest, + EvaluateProcessorVersionResponse, FetchProcessorTypesRequest, FetchProcessorTypesResponse, + GetEvaluationRequest, GetProcessorRequest, GetProcessorTypeRequest, GetProcessorVersionRequest, HumanReviewStatus, + ListEvaluationsRequest, + ListEvaluationsResponse, ListProcessorsRequest, ListProcessorsResponse, ListProcessorTypesRequest, @@ -70,11 +76,15 @@ SetDefaultProcessorVersionMetadata, SetDefaultProcessorVersionRequest, SetDefaultProcessorVersionResponse, + TrainProcessorVersionMetadata, + TrainProcessorVersionRequest, + TrainProcessorVersionResponse, UndeployProcessorVersionMetadata, UndeployProcessorVersionRequest, UndeployProcessorVersionResponse, ) from .types.document_schema import DocumentSchema +from .types.evaluation import Evaluation, EvaluationReference from .types.geometry import BoundingPoly, NormalizedVertex, Vertex from .types.operation_metadata import CommonOperationMetadata from .types.processor import Processor, ProcessorVersion @@ -107,15 +117,23 @@ "EnableProcessorMetadata", "EnableProcessorRequest", "EnableProcessorResponse", + "EvaluateProcessorVersionMetadata", + "EvaluateProcessorVersionRequest", + "EvaluateProcessorVersionResponse", + "Evaluation", + "EvaluationReference", "FetchProcessorTypesRequest", "FetchProcessorTypesResponse", "GcsDocument", "GcsDocuments", "GcsPrefix", + "GetEvaluationRequest", "GetProcessorRequest", "GetProcessorTypeRequest", "GetProcessorVersionRequest", "HumanReviewStatus", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "ListProcessorTypesRequest", "ListProcessorTypesResponse", "ListProcessorVersionsRequest", @@ -135,6 +153,9 @@ "SetDefaultProcessorVersionMetadata", "SetDefaultProcessorVersionRequest", "SetDefaultProcessorVersionResponse", + "TrainProcessorVersionMetadata", + "TrainProcessorVersionRequest", + "TrainProcessorVersionResponse", "UndeployProcessorVersionMetadata", "UndeployProcessorVersionRequest", "UndeployProcessorVersionResponse", diff --git a/google/cloud/documentai_v1/gapic_metadata.json b/google/cloud/documentai_v1/gapic_metadata.json index 2b34dcff..863c39a3 100644 --- a/google/cloud/documentai_v1/gapic_metadata.json +++ b/google/cloud/documentai_v1/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" @@ -65,6 +75,11 @@ "get_processor_version" ] }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, "ListProcessorTypes": { "methods": [ "list_processor_types" @@ -95,6 +110,11 @@ "set_default_processor_version" ] }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, "UndeployProcessorVersion": { "methods": [ "undeploy_processor_version" @@ -140,11 +160,21 @@ "enable_processor" ] }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, "FetchProcessorTypes": { "methods": [ "fetch_processor_types" ] }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, "GetProcessor": { "methods": [ "get_processor" @@ -160,6 +190,11 @@ "get_processor_version" ] }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, "ListProcessorTypes": { "methods": [ "list_processor_types" @@ -190,6 +225,11 @@ "set_default_processor_version" ] }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, "UndeployProcessorVersion": { "methods": [ "undeploy_processor_version" @@ -235,11 +275,21 @@ "enable_processor" ] }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, "FetchProcessorTypes": { "methods": [ "fetch_processor_types" ] }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, "GetProcessor": { "methods": [ "get_processor" @@ -255,6 +305,11 @@ "get_processor_version" ] }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, "ListProcessorTypes": { "methods": [ "list_processor_types" @@ -285,6 +340,11 @@ "set_default_processor_version" ] }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, "UndeployProcessorVersion": { "methods": [ "undeploy_processor_version" diff --git a/google/cloud/documentai_v1/services/document_processor_service/async_client.py b/google/cloud/documentai_v1/services/document_processor_service/async_client.py index 4a28256a..2360e046 100644 --- a/google/cloud/documentai_v1/services/document_processor_service/async_client.py +++ b/google/cloud/documentai_v1/services/document_processor_service/async_client.py @@ -55,6 +55,7 @@ document, document_processor_service, document_schema, + evaluation, ) from google.cloud.documentai_v1.types import processor from google.cloud.documentai_v1.types import processor as gcd_processor @@ -78,6 +79,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 ) @@ -1074,6 +1079,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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_train_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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_v1.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_v1.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[ @@ -2356,6 +2492,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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_get_evaluation(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.types.GetEvaluationRequest, dict]]): + The request object. Retrieves a specific Evaluation. + name (:class:`str`): + Required. The resource name of the + [Evaluation][google.cloud.documentai.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + async def sample_list_evaluations(): + # Create a client + client = documentai_v1.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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/google/cloud/documentai_v1/services/document_processor_service/client.py b/google/cloud/documentai_v1/services/document_processor_service/client.py index b541d7a8..e5c7e883 100644 --- a/google/cloud/documentai_v1/services/document_processor_service/client.py +++ b/google/cloud/documentai_v1/services/document_processor_service/client.py @@ -59,6 +59,7 @@ document, document_processor_service, document_schema, + evaluation, ) from google.cloud.documentai_v1.types import processor from google.cloud.documentai_v1.types import processor as gcd_processor @@ -197,6 +198,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, @@ -1330,6 +1357,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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_train_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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_v1.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_v1.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[ @@ -2625,6 +2785,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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_get_evaluation(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1.types.GetEvaluationRequest, dict]): + The request object. Retrieves a specific Evaluation. + name (str): + Required. The resource name of the + [Evaluation][google.cloud.documentai.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, + 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_v1 + + def sample_list_evaluations(): + # Create a client + client = documentai_v1.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1.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_v1.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.v1.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_v1.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) -> "DocumentProcessorServiceClient": return self diff --git a/google/cloud/documentai_v1/services/document_processor_service/pagers.py b/google/cloud/documentai_v1/services/document_processor_service/pagers.py index bbe91706..c38279ba 100644 --- a/google/cloud/documentai_v1/services/document_processor_service/pagers.py +++ b/google/cloud/documentai_v1/services/document_processor_service/pagers.py @@ -26,6 +26,7 @@ from google.cloud.documentai_v1.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_v1.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_v1.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_v1.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.documentai_v1.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_v1.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_v1.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_v1.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.documentai_v1.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/google/cloud/documentai_v1/services/document_processor_service/transports/base.py b/google/cloud/documentai_v1/services/document_processor_service/transports/base.py index 00055f71..4e895680 100644 --- a/google/cloud/documentai_v1/services/document_processor_service/transports/base.py +++ b/google/cloud/documentai_v1/services/document_processor_service/transports/base.py @@ -27,7 +27,7 @@ from google.oauth2 import service_account # type: ignore from google.cloud.documentai_v1 import gapic_version as package_version -from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import document_processor_service, evaluation from google.cloud.documentai_v1.types import processor from google.cloud.documentai_v1.types import processor as gcd_processor from google.cloud.documentai_v1.types import processor_type @@ -182,6 +182,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, @@ -247,6 +252,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): @@ -338,6 +358,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, @@ -440,6 +469,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/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py b/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py index 97eb8a7c..4ea00e32 100644 --- a/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py +++ b/google/cloud/documentai_v1/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_v1.types import document_processor_service +from google.cloud.documentai_v1.types import document_processor_service, evaluation from google.cloud.documentai_v1.types import processor from google.cloud.documentai_v1.types import processor as gcd_processor from google.cloud.documentai_v1.types import processor_type @@ -455,6 +455,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.v1.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, @@ -782,6 +812,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.v1.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.v1.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.v1.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/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py b/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py index e4d2128c..32cc18cd 100644 --- a/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py +++ b/google/cloud/documentai_v1/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_v1.types import document_processor_service +from google.cloud.documentai_v1.types import document_processor_service, evaluation from google.cloud.documentai_v1.types import processor from google.cloud.documentai_v1.types import processor as gcd_processor from google.cloud.documentai_v1.types import processor_type @@ -461,6 +461,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.v1.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, @@ -793,6 +823,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.v1.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.v1.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.v1.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/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py b/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py index f5569439..9a2faa01 100644 --- a/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py +++ b/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py @@ -46,7 +46,7 @@ from google.longrunning import operations_pb2 # type: ignore -from google.cloud.documentai_v1.types import document_processor_service +from google.cloud.documentai_v1.types import document_processor_service, evaluation from google.cloud.documentai_v1.types import processor from google.cloud.documentai_v1.types import processor as gcd_processor from google.cloud.documentai_v1.types import processor_type @@ -132,6 +132,14 @@ def post_enable_processor(self, response): logging.log(f"Received response: {response}") return response + def pre_evaluate_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_evaluate_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + def pre_fetch_processor_types(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -140,6 +148,14 @@ def post_fetch_processor_types(self, response): logging.log(f"Received response: {response}") return response + def pre_get_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_processor(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -164,6 +180,14 @@ def post_get_processor_version(self, response): logging.log(f"Received response: {response}") return response + def pre_list_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_processors(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -212,6 +236,14 @@ def post_set_default_processor_version(self, response): logging.log(f"Received response: {response}") return response + def pre_train_processor_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_train_processor_version(self, response): + logging.log(f"Received response: {response}") + return response + def pre_undeploy_processor_version(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -403,6 +435,32 @@ def post_enable_processor( """ return response + def pre_evaluate_processor_version( + self, + request: document_processor_service.EvaluateProcessorVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + document_processor_service.EvaluateProcessorVersionRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for evaluate_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_evaluate_processor_version( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for evaluate_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_fetch_processor_types( self, request: document_processor_service.FetchProcessorTypesRequest, @@ -428,6 +486,31 @@ def post_fetch_processor_types( """ return response + def pre_get_evaluation( + self, + request: document_processor_service.GetEvaluationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + document_processor_service.GetEvaluationRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_get_evaluation( + self, response: evaluation.Evaluation + ) -> evaluation.Evaluation: + """Post-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_get_processor( self, request: document_processor_service.GetProcessorRequest, @@ -501,6 +584,31 @@ def post_get_processor_version( """ return response + def pre_list_evaluations( + self, + request: document_processor_service.ListEvaluationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + document_processor_service.ListEvaluationsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_list_evaluations( + self, response: document_processor_service.ListEvaluationsResponse + ) -> document_processor_service.ListEvaluationsResponse: + """Post-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_list_processors( self, request: document_processor_service.ListProcessorsRequest, @@ -651,6 +759,32 @@ def post_set_default_processor_version( """ return response + def pre_train_processor_version( + self, + request: document_processor_service.TrainProcessorVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + document_processor_service.TrainProcessorVersionRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for train_processor_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentProcessorService server. + """ + return request, metadata + + def post_train_processor_version( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for train_processor_version + + Override in a subclass to manipulate the response + after it is returned by the DocumentProcessorService server but before + it is returned to user code. + """ + return response + def pre_undeploy_processor_version( self, request: document_processor_service.UndeployProcessorVersionRequest, @@ -1653,6 +1787,109 @@ def __call__( resp = self._interceptor.post_enable_processor(resp) return resp + class _EvaluateProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("EvaluateProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: document_processor_service.EvaluateProcessorVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the evaluate processor + version method over HTTP. + + Args: + request (~.document_processor_service.EvaluateProcessorVersionRequest): + The request object. Evaluates the given ProcessorVersion + against the supplied documents. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_evaluate_processor_version( + request, metadata + ) + pb_request = document_processor_service.EvaluateProcessorVersionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_evaluate_processor_version(resp) + return resp + class _FetchProcessorTypes(DocumentProcessorServiceRestStub): def __hash__(self): return hash("FetchProcessorTypes") @@ -1747,6 +1984,94 @@ def __call__( resp = self._interceptor.post_fetch_processor_types(resp) return resp + class _GetEvaluation(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("GetEvaluation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: document_processor_service.GetEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Call the get evaluation method over HTTP. + + Args: + request (~.document_processor_service.GetEvaluationRequest): + The request object. Retrieves a specific Evaluation. + 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: + ~.evaluation.Evaluation: + An evaluation of a ProcessorVersion's + performance. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_evaluation(request, metadata) + pb_request = document_processor_service.GetEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.Evaluation() + pb_resp = evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_evaluation(resp) + return resp + class _GetProcessor(DocumentProcessorServiceRestStub): def __hash__(self): return hash("GetProcessor") @@ -2030,6 +2355,96 @@ def __call__( resp = self._interceptor.post_get_processor_version(resp) return resp + class _ListEvaluations(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("ListEvaluations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: document_processor_service.ListEvaluationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document_processor_service.ListEvaluationsResponse: + r"""Call the list evaluations method over HTTP. + + Args: + request (~.document_processor_service.ListEvaluationsRequest): + The request object. Retrieves a list of evaluations for a + given ProcessorVersion. + + 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: + ~.document_processor_service.ListEvaluationsResponse: + The response from ListEvaluations. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations", + }, + ] + request, metadata = self._interceptor.pre_list_evaluations( + request, metadata + ) + pb_request = document_processor_service.ListEvaluationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_processor_service.ListEvaluationsResponse() + pb_resp = document_processor_service.ListEvaluationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_evaluations(resp) + return resp + class _ListProcessors(DocumentProcessorServiceRestStub): def __hash__(self): return hash("ListProcessors") @@ -2612,6 +3027,108 @@ def __call__( resp = self._interceptor.post_set_default_processor_version(resp) return resp + class _TrainProcessorVersion(DocumentProcessorServiceRestStub): + def __hash__(self): + return hash("TrainProcessorVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: document_processor_service.TrainProcessorVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the train processor version method over HTTP. + + Args: + request (~.document_processor_service.TrainProcessorVersionRequest): + The request object. Request message for the create + processor version method. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_train_processor_version( + request, metadata + ) + pb_request = document_processor_service.TrainProcessorVersionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_train_processor_version(resp) + return resp + class _UndeployProcessorVersion(DocumentProcessorServiceRestStub): def __hash__(self): return hash("UndeployProcessorVersion") @@ -2787,6 +3304,17 @@ def enable_processor( # In C++ this would require a dynamic_cast return self._EnableProcessor(self._session, self._host, self._interceptor) # type: ignore + @property + def evaluate_processor_version( + self, + ) -> Callable[ + [document_processor_service.EvaluateProcessorVersionRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EvaluateProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + @property def fetch_processor_types( self, @@ -2798,6 +3326,16 @@ def fetch_processor_types( # In C++ this would require a dynamic_cast return self._FetchProcessorTypes(self._session, self._host, self._interceptor) # type: ignore + @property + def get_evaluation( + self, + ) -> Callable[ + [document_processor_service.GetEvaluationRequest], evaluation.Evaluation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore + @property def get_processor( self, @@ -2830,6 +3368,17 @@ def get_processor_version( # In C++ this would require a dynamic_cast return self._GetProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + @property + def list_evaluations( + self, + ) -> Callable[ + [document_processor_service.ListEvaluationsRequest], + document_processor_service.ListEvaluationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore + @property def list_processors( self, @@ -2895,6 +3444,17 @@ def set_default_processor_version( # In C++ this would require a dynamic_cast return self._SetDefaultProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + @property + def train_processor_version( + self, + ) -> Callable[ + [document_processor_service.TrainProcessorVersionRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TrainProcessorVersion(self._session, self._host, self._interceptor) # type: ignore + @property def undeploy_processor_version( self, diff --git a/google/cloud/documentai_v1/types/__init__.py b/google/cloud/documentai_v1/types/__init__.py index 4d1bee7d..0525287c 100644 --- a/google/cloud/documentai_v1/types/__init__.py +++ b/google/cloud/documentai_v1/types/__init__.py @@ -41,12 +41,18 @@ EnableProcessorMetadata, EnableProcessorRequest, EnableProcessorResponse, + EvaluateProcessorVersionMetadata, + EvaluateProcessorVersionRequest, + EvaluateProcessorVersionResponse, FetchProcessorTypesRequest, FetchProcessorTypesResponse, + GetEvaluationRequest, GetProcessorRequest, GetProcessorTypeRequest, GetProcessorVersionRequest, HumanReviewStatus, + ListEvaluationsRequest, + ListEvaluationsResponse, ListProcessorsRequest, ListProcessorsResponse, ListProcessorTypesRequest, @@ -61,11 +67,15 @@ SetDefaultProcessorVersionMetadata, SetDefaultProcessorVersionRequest, SetDefaultProcessorVersionResponse, + TrainProcessorVersionMetadata, + TrainProcessorVersionRequest, + TrainProcessorVersionResponse, UndeployProcessorVersionMetadata, UndeployProcessorVersionRequest, UndeployProcessorVersionResponse, ) from .document_schema import DocumentSchema +from .evaluation import Evaluation, EvaluationReference from .geometry import BoundingPoly, NormalizedVertex, Vertex from .operation_metadata import CommonOperationMetadata from .processor import Processor, ProcessorVersion @@ -97,12 +107,18 @@ "EnableProcessorMetadata", "EnableProcessorRequest", "EnableProcessorResponse", + "EvaluateProcessorVersionMetadata", + "EvaluateProcessorVersionRequest", + "EvaluateProcessorVersionResponse", "FetchProcessorTypesRequest", "FetchProcessorTypesResponse", + "GetEvaluationRequest", "GetProcessorRequest", "GetProcessorTypeRequest", "GetProcessorVersionRequest", "HumanReviewStatus", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "ListProcessorsRequest", "ListProcessorsResponse", "ListProcessorTypesRequest", @@ -117,10 +133,15 @@ "SetDefaultProcessorVersionMetadata", "SetDefaultProcessorVersionRequest", "SetDefaultProcessorVersionResponse", + "TrainProcessorVersionMetadata", + "TrainProcessorVersionRequest", + "TrainProcessorVersionResponse", "UndeployProcessorVersionMetadata", "UndeployProcessorVersionRequest", "UndeployProcessorVersionResponse", "DocumentSchema", + "Evaluation", + "EvaluationReference", "BoundingPoly", "NormalizedVertex", "Vertex", diff --git a/google/cloud/documentai_v1/types/document.py b/google/cloud/documentai_v1/types/document.py index 00ad692c..66342176 100644 --- a/google/cloud/documentai_v1/types/document.py +++ b/google/cloud/documentai_v1/types/document.py @@ -1477,20 +1477,30 @@ class OperationType(proto.Enum): Add an element. REMOVE (2): Remove an element identified by ``parent``. + UPDATE (7): + Updates any fields within the given + provenance scope of the message. It 'overwrites' + the fields rather than replacing them. This is + especially relevant when we just want to update + a field value of an entity without also + affecting all the child properties. REPLACE (3): - Replace an element identified by ``parent``. - EVAL_REQUESTED (4): - Request human review for the element identified by + Currently unused. Replace an element identified by ``parent``. + EVAL_REQUESTED (4): + Deprecated. Request human review for the element identified + by ``parent``. EVAL_APPROVED (5): - Element is reviewed and approved at human - review, confidence will be set to 1.0. + Deprecated. Element is reviewed and approved + at human review, confidence will be set to 1.0. EVAL_SKIPPED (6): - Element is skipped in the validation process. + Deprecated. Element is skipped in the + validation process. """ OPERATION_TYPE_UNSPECIFIED = 0 ADD = 1 REMOVE = 2 + UPDATE = 7 REPLACE = 3 EVAL_REQUESTED = 4 EVAL_APPROVED = 5 @@ -1567,8 +1577,9 @@ class Revision(proto.Message): This field is a member of `oneof`_ ``source``. id (str): - Id of the revision. Unique within the - context of the document. + Id of the revision, internally generated by + doc proto storage. Unique within the context of + the document. parent (MutableSequence[int]): The revisions that this revision is based on. This can include one or more parent (when documents are merged.) This @@ -1579,7 +1590,9 @@ class Revision(proto.Message): eg. there are ``provenance.parent.revision`` fields that index into this field. create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the revision was created. + The time that the revision was created, + internally generated by doc proto storage at the + time of create. human_review (google.cloud.documentai_v1.types.Document.Revision.HumanReview): Human Review information of this revision. """ diff --git a/google/cloud/documentai_v1/types/document_processor_service.py b/google/cloud/documentai_v1/types/document_processor_service.py index ec45701e..15649291 100644 --- a/google/cloud/documentai_v1/types/document_processor_service.py +++ b/google/cloud/documentai_v1/types/document_processor_service.py @@ -23,6 +23,7 @@ from google.cloud.documentai_v1.types import document_schema as gcd_document_schema from google.cloud.documentai_v1.types import document as gcd_document from google.cloud.documentai_v1.types import document_io +from google.cloud.documentai_v1.types import evaluation as gcd_evaluation from google.cloud.documentai_v1.types import operation_metadata from google.cloud.documentai_v1.types import processor as gcd_processor from google.cloud.documentai_v1.types import processor_type @@ -67,9 +68,18 @@ "SetDefaultProcessorVersionRequest", "SetDefaultProcessorVersionResponse", "SetDefaultProcessorVersionMetadata", + "TrainProcessorVersionRequest", + "TrainProcessorVersionResponse", + "TrainProcessorVersionMetadata", "ReviewDocumentRequest", "ReviewDocumentResponse", "ReviewDocumentOperationMetadata", + "EvaluateProcessorVersionRequest", + "EvaluateProcessorVersionMetadata", + "EvaluateProcessorVersionResponse", + "GetEvaluationRequest", + "ListEvaluationsRequest", + "ListEvaluationsResponse", }, ) @@ -932,6 +942,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_v1.types.ProcessorVersion): + Required. The processor version to be + created. + document_schema (google.cloud.documentai_v1.types.DocumentSchema): + Optional. The schema the processor version + will be trained with. + input_data (google.cloud.documentai_v1.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_v1.types.BatchDocumentsInputConfig): + The documents used for training the new + version. + test_documents (google.cloud.documentai_v1.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_v1.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + training_dataset_validation (google.cloud.documentai_v1.types.TrainProcessorVersionMetadata.DatasetValidation): + The training dataset validation information. + test_dataset_validation (google.cloud.documentai_v1.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. @@ -1065,4 +1232,137 @@ class ReviewDocumentOperationMetadata(proto.Message): ) +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.v1.ProcessorVersion] + to evaluate. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + evaluation_documents (google.cloud.documentai_v1.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_v1.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.v1.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.v1.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_v1.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/google/cloud/documentai_v1/types/document_schema.py b/google/cloud/documentai_v1/types/document_schema.py index 2a2bba61..79630a76 100644 --- a/google/cloud/documentai_v1/types/document_schema.py +++ b/google/cloud/documentai_v1/types/document_schema.py @@ -80,7 +80,7 @@ class EntityType(proto.Message): The entity type that this type is derived from. For now, one and only one should be set. properties (MutableSequence[google.cloud.documentai_v1.types.DocumentSchema.EntityType.Property]): - Describing the nested structure, or + Description the nested structure, or composition of an entity. """ @@ -116,22 +116,30 @@ class Property(proto.Message): """ class OccurrenceType(proto.Enum): - r"""Types of occurrences of the entity type in the document. - Note: this represents the number of instances of an entity - types, not number of mentions of a given entity instance. + r"""Types of occurrences of the entity type in the document. This + represents the number of instances of instances of an entity, not + number of mentions of an entity. For example, a bank statement may + only have one ``account_number``, but this account number may be + mentioned in several places on the document. In this case the + 'account_number' would be considered a ``REQUIRED_ONCE`` entity + type. If, on the other hand, we expect a bank statement to contain + the status of multiple different accounts for the customers, the + occurrence type will be set to ``REQUIRED_MULTIPLE``. Values: OCCURRENCE_TYPE_UNSPECIFIED (0): Unspecified occurrence type. OPTIONAL_ONCE (1): There will be zero or one instance of this - entity type. + entity type. The same entity instance may be + mentioned multiple times. OPTIONAL_MULTIPLE (2): The entity type will appear zero or multiple times. REQUIRED_ONCE (3): The entity type will only appear exactly - once. + once. The same entity instance may be mentioned + multiple times. REQUIRED_MULTIPLE (4): The entity type will appear once or more times. diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/evaluation.py b/google/cloud/documentai_v1/types/evaluation.py similarity index 92% rename from owl-bot-staging/v1/google/cloud/documentai_v1/types/evaluation.py rename to google/cloud/documentai_v1/types/evaluation.py index 6483282d..bbcef991 100644 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/evaluation.py +++ b/google/cloud/documentai_v1/types/evaluation.py @@ -15,16 +15,14 @@ # from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import timestamp_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.cloud.documentai.v1', + package="google.cloud.documentai.v1", manifest={ - 'EvaluationReference', - 'Evaluation', + "EvaluationReference", + "Evaluation", }, ) @@ -55,15 +53,15 @@ class EvaluationReference(proto.Message): proto.STRING, number=2, ) - aggregate_metrics: 'Evaluation.Metrics' = proto.Field( + aggregate_metrics: "Evaluation.Metrics" = proto.Field( proto.MESSAGE, number=4, - message='Evaluation.Metrics', + message="Evaluation.Metrics", ) - aggregate_metrics_exact: 'Evaluation.Metrics' = proto.Field( + aggregate_metrics_exact: "Evaluation.Metrics" = proto.Field( proto.MESSAGE, number=5, - message='Evaluation.Metrics', + message="Evaluation.Metrics", ) @@ -219,10 +217,10 @@ class ConfidenceLevelMetrics(proto.Message): proto.FLOAT, number=1, ) - metrics: 'Evaluation.Metrics' = proto.Field( + metrics: "Evaluation.Metrics" = proto.Field( proto.MESSAGE, number=2, - message='Evaluation.Metrics', + message="Evaluation.Metrics", ) class MultiConfidenceMetrics(proto.Message): @@ -251,6 +249,7 @@ class MultiConfidenceMetrics(proto.Message): metrics_type (google.cloud.documentai_v1.types.Evaluation.MultiConfidenceMetrics.MetricsType): The metrics type for the label. """ + class MetricsType(proto.Enum): r"""A type that determines how metrics should be interpreted. @@ -272,15 +271,19 @@ class MetricsType(proto.Enum): METRICS_TYPE_UNSPECIFIED = 0 AGGREGATE = 1 - confidence_level_metrics: MutableSequence['Evaluation.ConfidenceLevelMetrics'] = proto.RepeatedField( + confidence_level_metrics: MutableSequence[ + "Evaluation.ConfidenceLevelMetrics" + ] = proto.RepeatedField( proto.MESSAGE, number=1, - message='Evaluation.ConfidenceLevelMetrics', + message="Evaluation.ConfidenceLevelMetrics", ) - confidence_level_metrics_exact: MutableSequence['Evaluation.ConfidenceLevelMetrics'] = proto.RepeatedField( + confidence_level_metrics_exact: MutableSequence[ + "Evaluation.ConfidenceLevelMetrics" + ] = proto.RepeatedField( proto.MESSAGE, number=4, - message='Evaluation.ConfidenceLevelMetrics', + message="Evaluation.ConfidenceLevelMetrics", ) auprc: float = proto.Field( proto.FLOAT, @@ -298,10 +301,10 @@ class MetricsType(proto.Enum): proto.FLOAT, number=6, ) - metrics_type: 'Evaluation.MultiConfidenceMetrics.MetricsType' = proto.Field( + metrics_type: "Evaluation.MultiConfidenceMetrics.MetricsType" = proto.Field( proto.ENUM, number=7, - enum='Evaluation.MultiConfidenceMetrics.MetricsType', + enum="Evaluation.MultiConfidenceMetrics.MetricsType", ) name: str = proto.Field( diff --git a/google/cloud/documentai_v1/types/processor.py b/google/cloud/documentai_v1/types/processor.py index b61d11f0..e50c4af8 100644 --- a/google/cloud/documentai_v1/types/processor.py +++ b/google/cloud/documentai_v1/types/processor.py @@ -19,6 +19,7 @@ import proto # type: ignore from google.cloud.documentai_v1.types import document_schema as gcd_document_schema +from google.cloud.documentai_v1.types import evaluation __protobuf__ = proto.module( package="google.cloud.documentai.v1", @@ -50,6 +51,9 @@ class ProcessorVersion(proto.Message): The state of the processor version. create_time (google.protobuf.timestamp_pb2.Timestamp): The time the processor version was created. + latest_evaluation (google.cloud.documentai_v1.types.EvaluationReference): + The most recently invoked evaluation for the + processor version. kms_key_name (str): The KMS key name used for encryption. kms_key_version_name (str): @@ -143,6 +147,11 @@ class DeprecationInfo(proto.Message): number=7, message=timestamp_pb2.Timestamp, ) + latest_evaluation: evaluation.EvaluationReference = proto.Field( + proto.MESSAGE, + number=8, + message=evaluation.EvaluationReference, + ) kms_key_name: str = proto.Field( proto.STRING, number=9, diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 46ab6093..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/documentai/__init__.py - google/cloud/documentai/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index b804f157..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/documentai *.py -recursive-include google/cloud/documentai_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 484a3c1c..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Documentai API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Documentai API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 960a15f0..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- 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. -# -# -# google-cloud-documentai documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-documentai" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-documentai-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-documentai.tex", - u"google-cloud-documentai Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-documentai", - u"Google Cloud Documentai Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-documentai", - u"google-cloud-documentai Documentation", - author, - "google-cloud-documentai", - "GAPIC library for Google Cloud Documentai API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst b/owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst deleted file mode 100644 index 5288f946..00000000 --- a/owl-bot-staging/v1/docs/documentai_v1/document_processor_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentProcessorService ------------------------------------------- - -.. automodule:: google.cloud.documentai_v1.services.document_processor_service - :members: - :inherited-members: - -.. automodule:: google.cloud.documentai_v1.services.document_processor_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/documentai_v1/services.rst b/owl-bot-staging/v1/docs/documentai_v1/services.rst deleted file mode 100644 index 551bb666..00000000 --- a/owl-bot-staging/v1/docs/documentai_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Documentai v1 API -=========================================== -.. toctree:: - :maxdepth: 2 - - document_processor_service diff --git a/owl-bot-staging/v1/docs/documentai_v1/types.rst b/owl-bot-staging/v1/docs/documentai_v1/types.rst deleted file mode 100644 index ddfb0aac..00000000 --- a/owl-bot-staging/v1/docs/documentai_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Documentai v1 API -======================================== - -.. automodule:: google.cloud.documentai_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index c907db5b..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - documentai_v1/services - documentai_v1/types diff --git a/owl-bot-staging/v1/google/cloud/documentai/__init__.py b/owl-bot-staging/v1/google/cloud/documentai/__init__.py deleted file mode 100644 index cc8377eb..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai/__init__.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- 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 google.cloud.documentai import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.documentai_v1.services.document_processor_service.client import DocumentProcessorServiceClient -from google.cloud.documentai_v1.services.document_processor_service.async_client import DocumentProcessorServiceAsyncClient - -from google.cloud.documentai_v1.types.barcode import Barcode -from google.cloud.documentai_v1.types.document import Document -from google.cloud.documentai_v1.types.document_io import BatchDocumentsInputConfig -from google.cloud.documentai_v1.types.document_io import DocumentOutputConfig -from google.cloud.documentai_v1.types.document_io import GcsDocument -from google.cloud.documentai_v1.types.document_io import GcsDocuments -from google.cloud.documentai_v1.types.document_io import GcsPrefix -from google.cloud.documentai_v1.types.document_io import RawDocument -from google.cloud.documentai_v1.types.document_processor_service import BatchProcessMetadata -from google.cloud.documentai_v1.types.document_processor_service import BatchProcessRequest -from google.cloud.documentai_v1.types.document_processor_service import BatchProcessResponse -from google.cloud.documentai_v1.types.document_processor_service import CreateProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorMetadata -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorMetadata -from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorResponse -from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorMetadata -from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorResponse -from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import FetchProcessorTypesRequest -from google.cloud.documentai_v1.types.document_processor_service import FetchProcessorTypesResponse -from google.cloud.documentai_v1.types.document_processor_service import GetEvaluationRequest -from google.cloud.documentai_v1.types.document_processor_service import GetProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import GetProcessorTypeRequest -from google.cloud.documentai_v1.types.document_processor_service import GetProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import HumanReviewStatus -from google.cloud.documentai_v1.types.document_processor_service import ListEvaluationsRequest -from google.cloud.documentai_v1.types.document_processor_service import ListEvaluationsResponse -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorsRequest -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorsResponse -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorTypesRequest -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorTypesResponse -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorVersionsRequest -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorVersionsResponse -from google.cloud.documentai_v1.types.document_processor_service import ProcessRequest -from google.cloud.documentai_v1.types.document_processor_service import ProcessResponse -from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentOperationMetadata -from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentRequest -from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentResponse -from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionResponse -from google.cloud.documentai_v1.types.document_schema import DocumentSchema -from google.cloud.documentai_v1.types.evaluation import Evaluation -from google.cloud.documentai_v1.types.evaluation import EvaluationReference -from google.cloud.documentai_v1.types.geometry import BoundingPoly -from google.cloud.documentai_v1.types.geometry import NormalizedVertex -from google.cloud.documentai_v1.types.geometry import Vertex -from google.cloud.documentai_v1.types.operation_metadata import CommonOperationMetadata -from google.cloud.documentai_v1.types.processor import Processor -from google.cloud.documentai_v1.types.processor import ProcessorVersion -from google.cloud.documentai_v1.types.processor_type import ProcessorType - -__all__ = ('DocumentProcessorServiceClient', - 'DocumentProcessorServiceAsyncClient', - 'Barcode', - 'Document', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorType', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai/gapic_version.py b/owl-bot-staging/v1/google/cloud/documentai/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/documentai/py.typed b/owl-bot-staging/v1/google/cloud/documentai/py.typed deleted file mode 100644 index 81b45001..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py deleted file mode 100644 index 35549fa5..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- 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 google.cloud.documentai_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.document_processor_service import DocumentProcessorServiceClient -from .services.document_processor_service import DocumentProcessorServiceAsyncClient - -from .types.barcode import Barcode -from .types.document import Document -from .types.document_io import BatchDocumentsInputConfig -from .types.document_io import DocumentOutputConfig -from .types.document_io import GcsDocument -from .types.document_io import GcsDocuments -from .types.document_io import GcsPrefix -from .types.document_io import RawDocument -from .types.document_processor_service import BatchProcessMetadata -from .types.document_processor_service import BatchProcessRequest -from .types.document_processor_service import BatchProcessResponse -from .types.document_processor_service import CreateProcessorRequest -from .types.document_processor_service import DeleteProcessorMetadata -from .types.document_processor_service import DeleteProcessorRequest -from .types.document_processor_service import DeleteProcessorVersionMetadata -from .types.document_processor_service import DeleteProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionMetadata -from .types.document_processor_service import DeployProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionResponse -from .types.document_processor_service import DisableProcessorMetadata -from .types.document_processor_service import DisableProcessorRequest -from .types.document_processor_service import DisableProcessorResponse -from .types.document_processor_service import EnableProcessorMetadata -from .types.document_processor_service import EnableProcessorRequest -from .types.document_processor_service import EnableProcessorResponse -from .types.document_processor_service import EvaluateProcessorVersionMetadata -from .types.document_processor_service import EvaluateProcessorVersionRequest -from .types.document_processor_service import EvaluateProcessorVersionResponse -from .types.document_processor_service import FetchProcessorTypesRequest -from .types.document_processor_service import FetchProcessorTypesResponse -from .types.document_processor_service import GetEvaluationRequest -from .types.document_processor_service import GetProcessorRequest -from .types.document_processor_service import GetProcessorTypeRequest -from .types.document_processor_service import GetProcessorVersionRequest -from .types.document_processor_service import HumanReviewStatus -from .types.document_processor_service import ListEvaluationsRequest -from .types.document_processor_service import ListEvaluationsResponse -from .types.document_processor_service import ListProcessorsRequest -from .types.document_processor_service import ListProcessorsResponse -from .types.document_processor_service import ListProcessorTypesRequest -from .types.document_processor_service import ListProcessorTypesResponse -from .types.document_processor_service import ListProcessorVersionsRequest -from .types.document_processor_service import ListProcessorVersionsResponse -from .types.document_processor_service import ProcessRequest -from .types.document_processor_service import ProcessResponse -from .types.document_processor_service import ReviewDocumentOperationMetadata -from .types.document_processor_service import ReviewDocumentRequest -from .types.document_processor_service import ReviewDocumentResponse -from .types.document_processor_service import SetDefaultProcessorVersionMetadata -from .types.document_processor_service import SetDefaultProcessorVersionRequest -from .types.document_processor_service import SetDefaultProcessorVersionResponse -from .types.document_processor_service import TrainProcessorVersionMetadata -from .types.document_processor_service import TrainProcessorVersionRequest -from .types.document_processor_service import TrainProcessorVersionResponse -from .types.document_processor_service import UndeployProcessorVersionMetadata -from .types.document_processor_service import UndeployProcessorVersionRequest -from .types.document_processor_service import UndeployProcessorVersionResponse -from .types.document_schema import DocumentSchema -from .types.evaluation import Evaluation -from .types.evaluation import EvaluationReference -from .types.geometry import BoundingPoly -from .types.geometry import NormalizedVertex -from .types.geometry import Vertex -from .types.operation_metadata import CommonOperationMetadata -from .types.processor import Processor -from .types.processor import ProcessorVersion -from .types.processor_type import ProcessorType - -__all__ = ( - 'DocumentProcessorServiceAsyncClient', -'Barcode', -'BatchDocumentsInputConfig', -'BatchProcessMetadata', -'BatchProcessRequest', -'BatchProcessResponse', -'BoundingPoly', -'CommonOperationMetadata', -'CreateProcessorRequest', -'DeleteProcessorMetadata', -'DeleteProcessorRequest', -'DeleteProcessorVersionMetadata', -'DeleteProcessorVersionRequest', -'DeployProcessorVersionMetadata', -'DeployProcessorVersionRequest', -'DeployProcessorVersionResponse', -'DisableProcessorMetadata', -'DisableProcessorRequest', -'DisableProcessorResponse', -'Document', -'DocumentOutputConfig', -'DocumentProcessorServiceClient', -'DocumentSchema', -'EnableProcessorMetadata', -'EnableProcessorRequest', -'EnableProcessorResponse', -'EvaluateProcessorVersionMetadata', -'EvaluateProcessorVersionRequest', -'EvaluateProcessorVersionResponse', -'Evaluation', -'EvaluationReference', -'FetchProcessorTypesRequest', -'FetchProcessorTypesResponse', -'GcsDocument', -'GcsDocuments', -'GcsPrefix', -'GetEvaluationRequest', -'GetProcessorRequest', -'GetProcessorTypeRequest', -'GetProcessorVersionRequest', -'HumanReviewStatus', -'ListEvaluationsRequest', -'ListEvaluationsResponse', -'ListProcessorTypesRequest', -'ListProcessorTypesResponse', -'ListProcessorVersionsRequest', -'ListProcessorVersionsResponse', -'ListProcessorsRequest', -'ListProcessorsResponse', -'NormalizedVertex', -'ProcessRequest', -'ProcessResponse', -'Processor', -'ProcessorType', -'ProcessorVersion', -'RawDocument', -'ReviewDocumentOperationMetadata', -'ReviewDocumentRequest', -'ReviewDocumentResponse', -'SetDefaultProcessorVersionMetadata', -'SetDefaultProcessorVersionRequest', -'SetDefaultProcessorVersionResponse', -'TrainProcessorVersionMetadata', -'TrainProcessorVersionRequest', -'TrainProcessorVersionResponse', -'UndeployProcessorVersionMetadata', -'UndeployProcessorVersionRequest', -'UndeployProcessorVersionResponse', -'Vertex', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json deleted file mode 100644 index 863c39a3..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json +++ /dev/null @@ -1,358 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.documentai_v1", - "protoPackage": "google.cloud.documentai.v1", - "schema": "1.0", - "services": { - "DocumentProcessorService": { - "clients": { - "grpc": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentProcessorServiceAsyncClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/py.typed b/owl-bot-staging/v1/google/cloud/documentai_v1/py.typed deleted file mode 100644 index 81b45001..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- 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. -# diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py deleted file mode 100644 index 0e16e431..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- 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 .client import DocumentProcessorServiceClient -from .async_client import DocumentProcessorServiceAsyncClient - -__all__ = ( - 'DocumentProcessorServiceClient', - 'DocumentProcessorServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py deleted file mode 100644 index c3f43e68..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py +++ /dev/null @@ -1,2979 +0,0 @@ -# -*- 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 collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.documentai_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1.services.document_processor_service import pagers -from google.cloud.documentai_v1.types import document -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import document_schema -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .client import DocumentProcessorServiceClient - - -class DocumentProcessorServiceAsyncClient: - """Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - """ - - _client: DocumentProcessorServiceClient - - 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) - parse_human_review_config_path = staticmethod(DocumentProcessorServiceClient.parse_human_review_config_path) - processor_path = staticmethod(DocumentProcessorServiceClient.processor_path) - parse_processor_path = staticmethod(DocumentProcessorServiceClient.parse_processor_path) - processor_type_path = staticmethod(DocumentProcessorServiceClient.processor_type_path) - parse_processor_type_path = staticmethod(DocumentProcessorServiceClient.parse_processor_type_path) - processor_version_path = staticmethod(DocumentProcessorServiceClient.processor_version_path) - parse_processor_version_path = staticmethod(DocumentProcessorServiceClient.parse_processor_version_path) - common_billing_account_path = staticmethod(DocumentProcessorServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentProcessorServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentProcessorServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentProcessorServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentProcessorServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentProcessorServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentProcessorServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentProcessorServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentProcessorServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentProcessorServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_info.__func__(DocumentProcessorServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_file.__func__(DocumentProcessorServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentProcessorServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentProcessorServiceClient).get_transport_class, type(DocumentProcessorServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.DocumentProcessorServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DocumentProcessorServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. 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_v1 - - async def sample_process_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ProcessRequest, dict]]): - The request object. Request message for the process - document method. - name (:class:`str`): - Required. The resource name of the - [Processor][google.cloud.documentai.v1.Processor] or - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to use for processing. If a - [Processor][google.cloud.documentai.v1.Processor] is - specified, the server will use its [default - version][google.cloud.documentai.v1.Processor.default_processor_version]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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_v1.types.ProcessResponse: - Response message for the process - document 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([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.ProcessRequest(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.process_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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 batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. 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_v1 - - async def sample_batch_process_documents(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.BatchProcessRequest, dict]]): - The request object. Request message for batch process - document method. - name (:class:`str`): - Required. The resource name of - [Processor][google.cloud.documentai.v1.Processor] or - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.documentai_v1.types.BatchProcessResponse` - Response message for batch process document 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([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.BatchProcessRequest(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.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - async def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - .. 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_v1 - - async def sample_fetch_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.fetch_processor_types(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.FetchProcessorTypesRequest, dict]]): - The request object. Request message for fetch processor - types. - parent (:class:`str`): - Required. The project of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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_v1.types.FetchProcessorTypesResponse: - Response message for fetch processor - types. - - """ - # 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.FetchProcessorTypesRequest(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.fetch_processor_types, - 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, - ) - - # Done; return the response. - return response - - async def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesAsyncPager: - r"""Lists the processor types that exist. - - .. 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_v1 - - async def sample_list_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorTypesRequest, dict]]): - The request object. Request message for list processor - types. - parent (:class:`str`): - Required. The location of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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_v1.services.document_processor_service.pagers.ListProcessorTypesAsyncPager: - Response message for list processor - types. - 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.ListProcessorTypesRequest(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_processor_types, - 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.ListProcessorTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. 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_v1 - - async def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorTypeRequest, dict]]): - The request object. Request message for get processor. - name (:class:`str`): - Required. The processor type resource - name. - - 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_v1.types.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # 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.GetProcessorTypeRequest(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_processor_type, - 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_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsAsyncPager: - r"""Lists all processors which belong to this project. - - .. 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_v1 - - async def sample_list_processors(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorsRequest, dict]]): - The request object. Request message for list all - processors belongs to a project. - parent (:class:`str`): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - 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_v1.services.document_processor_service.pagers.ListProcessorsAsyncPager: - Response message for list processors. - 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.ListProcessorsRequest(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_processors, - 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.ListProcessorsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. 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_v1 - - async def sample_get_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorRequest, dict]]): - The request object. Request message for get processor. - name (:class:`str`): - Required. The processor resource - name. - - 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_v1.types.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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.GetProcessorRequest(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_processor, - 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 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - async def sample_train_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.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_v1.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_v1.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_v1.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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. 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_v1 - - async def sample_get_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorVersionRequest, dict]]): - The request object. Request message for get processor - version. - name (:class:`str`): - Required. The processor resource - name. - - 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_v1.types.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pre-trained by Google internally or - up-trained by the customer. At a time, a - processor can only have one default - version version. So the processor's - behavior (when processing documents) is - defined by a default version - - """ - # 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.GetProcessorVersionRequest(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_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(( - ("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_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsAsyncPager: - r"""Lists all versions of a processor. - - .. 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_v1 - - async def sample_list_processor_versions(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorVersionsRequest, dict]]): - The request object. Request message for list all - processor versions belongs to a processor. - parent (:class:`str`): - Required. The parent (project, location and processor) - to list all versions. 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. - 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_v1.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager: - Response message for list processors. - 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.ListProcessorVersionsRequest(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_processor_versions, - 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.ListProcessorVersionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. 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_v1 - - async def sample_delete_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_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_v1.types.DeleteProcessorVersionRequest, dict]]): - The request object. Request message for the delete - processor version method. - name (:class:`str`): - Required. The processor version - resource name to be deleted. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorVersionRequest(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.delete_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(( - ("name", request.name), - )), - ) - - # 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, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deploys the 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_v1 - - async def sample_deploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_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_v1.types.DeployProcessorVersionRequest, dict]]): - The request object. Request message for the deploy - processor version method. - name (:class:`str`): - Required. The processor version - resource name to be deployed. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.documentai_v1.types.DeployProcessorVersionResponse` - Response message for the deploy processor version - 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([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.DeployProcessorVersionRequest(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.deploy_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(( - ("name", request.name), - )), - ) - - # 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.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Undeploys the 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_v1 - - async def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_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_v1.types.UndeployProcessorVersionRequest, dict]]): - The request object. Request message for the undeploy - processor version method. - name (:class:`str`): - Required. The processor version - resource name to be undeployed. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.documentai_v1.types.UndeployProcessorVersionResponse` - Response message for the undeploy processor version - 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([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.UndeployProcessorVersionRequest(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.undeploy_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(( - ("name", request.name), - )), - ) - - # 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.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - .. 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_v1 - - async def sample_create_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.CreateProcessorRequest, dict]]): - The request object. Request message for create a - processor. Notice this request is sent to a regionalized - backend service, and if the processor type is not - available on that region, the creation will fail. - parent (:class:`str`): - Required. The parent (project and location) under which - to create the processor. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor (:class:`google.cloud.documentai_v1.types.Processor`): - Required. The processor to be created, requires - [processor_type] and [display_name] to be set. Also, the - processor is under CMEK if CMEK fields are set. - - This corresponds to the ``processor`` 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_v1.types.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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]) - 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.CreateProcessorRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor is not None: - request.processor = processor - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_processor, - 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, - ) - - # Done; return the response. - return response - - async def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. 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_v1 - - async def sample_delete_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.DeleteProcessorRequest, dict]]): - The request object. Request message for the delete - processor method. - name (:class:`str`): - Required. The processor resource name - to be deleted. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorRequest(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.delete_processor, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - async def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Enables a processor - - .. 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_v1 - - async def sample_enable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.EnableProcessorRequest, dict]]): - The request object. Request message for the enable - processor method. - 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_v1.types.EnableProcessorResponse` Response message for the enable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - request = document_processor_service.EnableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.enable_processor, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Disables a processor - - .. 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_v1 - - async def sample_disable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.DisableProcessorRequest, dict]]): - The request object. Request message for the disable - processor method. - 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_v1.types.DisableProcessorResponse` Response message for the disable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - request = document_processor_service.DisableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.disable_processor, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - .. 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_v1 - - async def sample_set_default_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_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_v1.types.SetDefaultProcessorVersionRequest, dict]]): - The request object. Request message for the set default - processor version method. - 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_v1.types.SetDefaultProcessorVersionResponse` - Response message for set default processor version - method. - - """ - # Create or coerce a protobuf request object. - request = document_processor_service.SetDefaultProcessorVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_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", request.processor), - )), - ) - - # 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.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. 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_v1 - - async def sample_review_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ReviewDocumentRequest, dict]]): - The request object. Request message for review document - method. - human_review_config (:class:`str`): - Required. The resource name of the - HumanReviewConfig that the document will - be reviewed with. - - This corresponds to the ``human_review_config`` 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_v1.types.ReviewDocumentResponse` - Response message for review document 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([human_review_config]) - 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.ReviewDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if human_review_config is not None: - request.human_review_config = human_review_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.review_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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(( - ("human_review_config", request.human_review_config), - )), - ) - - # 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.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - async def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.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_v1.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.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - async def sample_get_evaluation(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.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_v1.types.GetEvaluationRequest, dict]]): - The request object. Retrieves a specific Evaluation. - name (:class:`str`): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - async def sample_list_evaluations(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.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_v1.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.v1.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_v1.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, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - 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 __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py deleted file mode 100644 index 1418ef7a..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py +++ /dev/null @@ -1,3196 +0,0 @@ -# -*- 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 collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.documentai_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1.services.document_processor_service import pagers -from google.cloud.documentai_v1.types import document -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import document_schema -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentProcessorServiceGrpcTransport -from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .transports.rest import DocumentProcessorServiceRestTransport - - -class DocumentProcessorServiceClientMeta(type): - """Metaclass for the DocumentProcessorService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] - _transport_registry["grpc"] = DocumentProcessorServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentProcessorServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentProcessorServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentProcessorServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentProcessorServiceClient(metaclass=DocumentProcessorServiceClientMeta): - """Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "documentai.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client - instance. - """ - 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,location: str,processor: str,) -> str: - """Returns a fully-qualified human_review_config string.""" - return "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_human_review_config_path(path: str) -> Dict[str,str]: - """Parses a human_review_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/humanReviewConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified processor string.""" - return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_processor_path(path: str) -> Dict[str,str]: - """Parses a processor path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_type_path(project: str,location: str,processor_type: str,) -> str: - """Returns a fully-qualified processor_type string.""" - return "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - - @staticmethod - def parse_processor_type_path(path: str) -> Dict[str,str]: - """Parses a processor_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processorTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_version_path(project: str,location: str,processor: str,processor_version: str,) -> str: - """Returns a fully-qualified processor_version string.""" - return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - - @staticmethod - def parse_processor_version_path(path: str) -> Dict[str,str]: - """Parses a processor_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentProcessorServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DocumentProcessorServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentProcessorServiceTransport): - # transport is a DocumentProcessorServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. 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_v1 - - def sample_process_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ProcessRequest, dict]): - The request object. Request message for the process - document method. - name (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1.Processor] or - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to use for processing. If a - [Processor][google.cloud.documentai.v1.Processor] is - specified, the server will use its [default - version][google.cloud.documentai.v1.Processor.default_processor_version]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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_v1.types.ProcessResponse: - Response message for the process - document 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([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.ProcessRequest. - # 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.ProcessRequest): - request = document_processor_service.ProcessRequest(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.process_document] - - # 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 batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. 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_v1 - - def sample_batch_process_documents(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.BatchProcessRequest, dict]): - The request object. Request message for batch process - document method. - name (str): - Required. The resource name of - [Processor][google.cloud.documentai.v1.Processor] or - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.documentai_v1.types.BatchProcessResponse` - Response message for batch process document 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([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.BatchProcessRequest. - # 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.BatchProcessRequest): - request = document_processor_service.BatchProcessRequest(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.batch_process_documents] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - .. 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_v1 - - def sample_fetch_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = client.fetch_processor_types(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.FetchProcessorTypesRequest, dict]): - The request object. Request message for fetch processor - types. - parent (str): - Required. The project of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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_v1.types.FetchProcessorTypesResponse: - Response message for fetch processor - types. - - """ - # 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.FetchProcessorTypesRequest. - # 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.FetchProcessorTypesRequest): - request = document_processor_service.FetchProcessorTypesRequest(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.fetch_processor_types] - - # 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, - ) - - # Done; return the response. - return response - - def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesPager: - r"""Lists the processor types that exist. - - .. 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_v1 - - def sample_list_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ListProcessorTypesRequest, dict]): - The request object. Request message for list processor - types. - parent (str): - Required. The location of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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_v1.services.document_processor_service.pagers.ListProcessorTypesPager: - Response message for list processor - types. - 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.ListProcessorTypesRequest. - # 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.ListProcessorTypesRequest): - request = document_processor_service.ListProcessorTypesRequest(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_processor_types] - - # 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.ListProcessorTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. 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_v1 - - def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetProcessorTypeRequest, dict]): - The request object. Request message for get processor. - name (str): - Required. The processor type resource - name. - - 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_v1.types.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # 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.GetProcessorTypeRequest. - # 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.GetProcessorTypeRequest): - request = document_processor_service.GetProcessorTypeRequest(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_processor_type] - - # 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_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsPager: - r"""Lists all processors which belong to this project. - - .. 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_v1 - - def sample_list_processors(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ListProcessorsRequest, dict]): - The request object. Request message for list all - processors belongs to a project. - parent (str): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - 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_v1.services.document_processor_service.pagers.ListProcessorsPager: - Response message for list processors. - 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.ListProcessorsRequest. - # 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.ListProcessorsRequest): - request = document_processor_service.ListProcessorsRequest(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_processors] - - # 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.ListProcessorsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. 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_v1 - - def sample_get_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetProcessorRequest, dict]): - The request object. Request message for get processor. - name (str): - Required. The processor resource - name. - - 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_v1.types.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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.GetProcessorRequest. - # 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.GetProcessorRequest): - request = document_processor_service.GetProcessorRequest(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_processor] - - # 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 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - def sample_train_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.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_v1.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_v1.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_v1.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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. 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_v1 - - def sample_get_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetProcessorVersionRequest, dict]): - The request object. Request message for get processor - version. - name (str): - Required. The processor resource - name. - - 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_v1.types.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pre-trained by Google internally or - up-trained by the customer. At a time, a - processor can only have one default - version version. So the processor's - behavior (when processing documents) is - defined by a default version - - """ - # 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.GetProcessorVersionRequest. - # 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.GetProcessorVersionRequest): - request = document_processor_service.GetProcessorVersionRequest(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_processor_version] - - # 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_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsPager: - r"""Lists all versions of a processor. - - .. 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_v1 - - def sample_list_processor_versions(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ListProcessorVersionsRequest, dict]): - The request object. Request message for list all - processor versions belongs to a processor. - parent (str): - Required. The parent (project, location and processor) - to list all versions. 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. - 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_v1.services.document_processor_service.pagers.ListProcessorVersionsPager: - Response message for list processors. - 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.ListProcessorVersionsRequest. - # 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.ListProcessorVersionsRequest): - request = document_processor_service.ListProcessorVersionsRequest(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_processor_versions] - - # 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.ListProcessorVersionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. 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_v1 - - def sample_delete_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DeleteProcessorVersionRequest, dict]): - The request object. Request message for the delete - processor version method. - name (str): - Required. The processor version - resource name to be deleted. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorVersionRequest. - # 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.DeleteProcessorVersionRequest): - request = document_processor_service.DeleteProcessorVersionRequest(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.delete_processor_version] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deploys the 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_v1 - - def sample_deploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DeployProcessorVersionRequest, dict]): - The request object. Request message for the deploy - processor version method. - name (str): - Required. The processor version - resource name to be deployed. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.documentai_v1.types.DeployProcessorVersionResponse` - Response message for the deploy processor version - 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([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.DeployProcessorVersionRequest. - # 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.DeployProcessorVersionRequest): - request = document_processor_service.DeployProcessorVersionRequest(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.deploy_processor_version] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Undeploys the 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_v1 - - def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.UndeployProcessorVersionRequest, dict]): - The request object. Request message for the undeploy - processor version method. - name (str): - Required. The processor version - resource name to be undeployed. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.documentai_v1.types.UndeployProcessorVersionResponse` - Response message for the undeploy processor version - 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([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.UndeployProcessorVersionRequest. - # 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.UndeployProcessorVersionRequest): - request = document_processor_service.UndeployProcessorVersionRequest(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.undeploy_processor_version] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - .. 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_v1 - - def sample_create_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.CreateProcessorRequest, dict]): - The request object. Request message for create a - processor. Notice this request is sent to a regionalized - backend service, and if the processor type is not - available on that region, the creation will fail. - parent (str): - Required. The parent (project and location) under which - to create the processor. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor (google.cloud.documentai_v1.types.Processor): - Required. The processor to be created, requires - [processor_type] and [display_name] to be set. Also, the - processor is under CMEK if CMEK fields are set. - - This corresponds to the ``processor`` 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_v1.types.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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]) - 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.CreateProcessorRequest. - # 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.CreateProcessorRequest): - request = document_processor_service.CreateProcessorRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor is not None: - request.processor = processor - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_processor] - - # 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, - ) - - # Done; return the response. - return response - - def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. 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_v1 - - def sample_delete_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DeleteProcessorRequest, dict]): - The request object. Request message for the delete - processor method. - name (str): - Required. The processor resource name - to be deleted. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorRequest. - # 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.DeleteProcessorRequest): - request = document_processor_service.DeleteProcessorRequest(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.delete_processor] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Enables a processor - - .. 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_v1 - - def sample_enable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.EnableProcessorRequest, dict]): - The request object. Request message for the enable - processor method. - 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_v1.types.EnableProcessorResponse` Response message for the enable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.EnableProcessorRequest. - # 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.EnableProcessorRequest): - request = document_processor_service.EnableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.enable_processor] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Disables a processor - - .. 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_v1 - - def sample_disable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DisableProcessorRequest, dict]): - The request object. Request message for the disable - processor method. - 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_v1.types.DisableProcessorResponse` Response message for the disable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.DisableProcessorRequest. - # 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.DisableProcessorRequest): - request = document_processor_service.DisableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.disable_processor] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - .. 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_v1 - - def sample_set_default_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest, dict]): - The request object. Request message for the set default - processor version method. - 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_v1.types.SetDefaultProcessorVersionResponse` - Response message for set default processor version - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.SetDefaultProcessorVersionRequest. - # 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.SetDefaultProcessorVersionRequest): - request = document_processor_service.SetDefaultProcessorVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_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", request.processor), - )), - ) - - # 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.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. 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_v1 - - def sample_review_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ReviewDocumentRequest, dict]): - The request object. Request message for review document - method. - human_review_config (str): - Required. The resource name of the - HumanReviewConfig that the document will - be reviewed with. - - This corresponds to the ``human_review_config`` 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_v1.types.ReviewDocumentResponse` - Response message for review document 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([human_review_config]) - 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.ReviewDocumentRequest. - # 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.ReviewDocumentRequest): - request = document_processor_service.ReviewDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if human_review_config is not None: - request.human_review_config = human_review_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.review_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("human_review_config", request.human_review_config), - )), - ) - - # 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.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.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_v1.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.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - def sample_get_evaluation(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = client.get_evaluation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetEvaluationRequest, dict]): - The request object. Retrieves a specific Evaluation. - name (str): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1.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_v1.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: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1 - - def sample_list_evaluations(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.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_v1.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.v1.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_v1.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) -> "DocumentProcessorServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py deleted file mode 100644 index beb09ba8..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py +++ /dev/null @@ -1,505 +0,0 @@ -# -*- 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 Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor_type - - -class ListProcessorTypesPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` - 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.ListProcessorTypesResponse], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - 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_v1.types.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorTypesResponse): - 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: - 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[processor_type.ProcessorType]: - for page in self.pages: - yield from page.processor_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorTypesAsyncPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` - 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.ListProcessorTypesResponse]], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - 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_v1.types.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorTypesResponse): - 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: - 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[processor_type.ProcessorType]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` - 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.ListProcessorsResponse], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - 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_v1.types.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorsResponse): - 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.ListProcessorsRequest(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.ListProcessorsResponse]: - 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[processor.Processor]: - for page in self.pages: - yield from page.processors - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsAsyncPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` - 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.ListProcessorsResponse]], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - 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_v1.types.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorsResponse): - 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.ListProcessorsRequest(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.ListProcessorsResponse]: - 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[processor.Processor]: - async def async_generator(): - async for page in self.pages: - for response in page.processors: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` - 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.ListProcessorVersionsResponse], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - 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_v1.types.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorVersionsResponse): - 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: - 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[processor.ProcessorVersion]: - for page in self.pages: - yield from page.processor_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsAsyncPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` - 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.ListProcessorVersionsResponse]], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - 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_v1.types.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorVersionsResponse): - 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: - 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[processor.ProcessorVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_versions: - yield response - - return 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_v1.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_v1.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_v1.types.ListEvaluationsRequest): - The initial request object. - response (google.cloud.documentai_v1.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_v1.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_v1.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_v1.types.ListEvaluationsRequest): - The initial request object. - response (google.cloud.documentai_v1.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/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py deleted file mode 100644 index cb5f6e80..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- 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 collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentProcessorServiceTransport -from .grpc import DocumentProcessorServiceGrpcTransport -from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .rest import DocumentProcessorServiceRestTransport -from .rest import DocumentProcessorServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] -_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentProcessorServiceRestTransport - -__all__ = ( - 'DocumentProcessorServiceTransport', - 'DocumentProcessorServiceGrpcTransport', - 'DocumentProcessorServiceGrpcAsyncIOTransport', - 'DocumentProcessorServiceRestTransport', - 'DocumentProcessorServiceRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py deleted file mode 100644 index f2a2f426..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py +++ /dev/null @@ -1,519 +0,0 @@ -# -*- 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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.documentai_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentProcessorServiceTransport(abc.ABC): - """Abstract transport class for DocumentProcessorService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'documentai.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.process_document: gapic_v1.method.wrap_method( - self.process_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.batch_process_documents: gapic_v1.method.wrap_method( - self.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.fetch_processor_types: gapic_v1.method.wrap_method( - self.fetch_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.list_processor_types: gapic_v1.method.wrap_method( - self.list_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.get_processor_type: gapic_v1.method.wrap_method( - self.get_processor_type, - default_timeout=None, - client_info=client_info, - ), - self.list_processors: gapic_v1.method.wrap_method( - self.list_processors, - default_timeout=None, - client_info=client_info, - ), - self.get_processor: gapic_v1.method.wrap_method( - self.get_processor, - 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, - client_info=client_info, - ), - self.list_processor_versions: gapic_v1.method.wrap_method( - self.list_processor_versions, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor_version: gapic_v1.method.wrap_method( - self.delete_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.deploy_processor_version: gapic_v1.method.wrap_method( - self.deploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.undeploy_processor_version: gapic_v1.method.wrap_method( - self.undeploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.create_processor: gapic_v1.method.wrap_method( - self.create_processor, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor: gapic_v1.method.wrap_method( - self.delete_processor, - default_timeout=None, - client_info=client_info, - ), - self.enable_processor: gapic_v1.method.wrap_method( - self.enable_processor, - default_timeout=None, - client_info=client_info, - ), - self.disable_processor: gapic_v1.method.wrap_method( - self.disable_processor, - default_timeout=None, - client_info=client_info, - ), - self.set_default_processor_version: gapic_v1.method.wrap_method( - self.set_default_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.review_document: gapic_v1.method.wrap_method( - self.review_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - 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): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - Union[ - document_processor_service.ProcessResponse, - Awaitable[document_processor_service.ProcessResponse] - ]]: - raise NotImplementedError() - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - Union[ - document_processor_service.FetchProcessorTypesResponse, - Awaitable[document_processor_service.FetchProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Union[ - document_processor_service.ListProcessorTypesResponse, - Awaitable[document_processor_service.ListProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Union[ - processor_type.ProcessorType, - Awaitable[processor_type.ProcessorType] - ]]: - raise NotImplementedError() - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Union[ - document_processor_service.ListProcessorsResponse, - Awaitable[document_processor_service.ListProcessorsResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Union[ - processor.Processor, - Awaitable[processor.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) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Union[ - processor.ProcessorVersion, - Awaitable[processor.ProcessorVersion] - ]]: - raise NotImplementedError() - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Union[ - document_processor_service.ListProcessorVersionsResponse, - Awaitable[document_processor_service.ListProcessorVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Union[ - gcd_processor.Processor, - Awaitable[gcd_processor.Processor] - ]]: - raise NotImplementedError() - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - 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, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentProcessorServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py deleted file mode 100644 index 4b6370cc..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py +++ /dev/null @@ -1,945 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentProcessorServiceGrpcTransport(DocumentProcessorServiceTransport): - """gRPC backend transport for DocumentProcessorService. - - Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessRequest], - ~.ProcessResponse]: - 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 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ProcessDocument', - request_serializer=document_processor_service.ProcessRequest.serialize, - response_deserializer=document_processor_service.ProcessResponse.deserialize, - ) - return self._stubs['process_document'] - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessRequest], - ~.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 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/BatchProcessDocuments', - request_serializer=document_processor_service.BatchProcessRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - r"""Return a callable for the fetch processor types method over gRPC. - - Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - ~.FetchProcessorTypesResponse]: - 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 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - ~.ListProcessorTypesResponse]: - 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_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - ~.ProcessorType]: - 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_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - ~.ListProcessorsResponse]: - 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_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - ~.Processor]: - 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_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - 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.v1.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) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - ~.ProcessorVersion]: - 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_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - ~.ListProcessorVersionsResponse]: - 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_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - ~.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 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - ~.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 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - ~.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 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - ~.Processor]: - 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 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - ~.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 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - ~.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 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - ~.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 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - ~.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 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - ~.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 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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.v1.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.v1.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.v1.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() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentProcessorServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py deleted file mode 100644 index 25aa77d2..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,944 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentProcessorServiceGrpcTransport - - -class DocumentProcessorServiceGrpcAsyncIOTransport(DocumentProcessorServiceTransport): - """gRPC AsyncIO backend transport for DocumentProcessorService. - - Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - Awaitable[document_processor_service.ProcessResponse]]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessRequest], - Awaitable[~.ProcessResponse]]: - 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 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ProcessDocument', - request_serializer=document_processor_service.ProcessRequest.serialize, - response_deserializer=document_processor_service.ProcessResponse.deserialize, - ) - return self._stubs['process_document'] - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessRequest], - 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 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/BatchProcessDocuments', - request_serializer=document_processor_service.BatchProcessRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - Awaitable[document_processor_service.FetchProcessorTypesResponse]]: - r"""Return a callable for the fetch processor types method over gRPC. - - Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - Awaitable[~.FetchProcessorTypesResponse]]: - 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 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Awaitable[document_processor_service.ListProcessorTypesResponse]]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - Awaitable[~.ListProcessorTypesResponse]]: - 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_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Awaitable[processor_type.ProcessorType]]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - Awaitable[~.ProcessorType]]: - 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_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Awaitable[document_processor_service.ListProcessorsResponse]]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - Awaitable[~.ListProcessorsResponse]]: - 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_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Awaitable[processor.Processor]]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - Awaitable[~.Processor]]: - 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_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - 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.v1.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) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Awaitable[processor.ProcessorVersion]]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - Awaitable[~.ProcessorVersion]]: - 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_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Awaitable[document_processor_service.ListProcessorVersionsResponse]]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - Awaitable[~.ListProcessorVersionsResponse]]: - 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_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - 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 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - 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 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - 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 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Awaitable[gcd_processor.Processor]]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - Awaitable[~.Processor]]: - 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 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - 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 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - 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 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - 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 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - 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 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - 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 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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.v1.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.v1.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.v1.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() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'DocumentProcessorServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py deleted file mode 100644 index 383660ce..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py +++ /dev/null @@ -1,3288 +0,0 @@ -# -*- 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentProcessorServiceRestInterceptor: - """Interceptor for DocumentProcessorService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DocumentProcessorServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentProcessorServiceInterceptor(DocumentProcessorServiceRestInterceptor): - def pre_batch_process_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_process_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_deploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_deploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_disable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_disable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_enable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_enable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_evaluate_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_evaluate_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_fetch_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_fetch_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_evaluation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_evaluation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_evaluations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_evaluations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processors(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processors(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_process_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_process_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_review_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_review_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_default_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_default_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_train_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_train_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undeploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undeploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentProcessorServiceRestTransport(interceptor=MyCustomDocumentProcessorServiceInterceptor()) - client = DocumentProcessorServiceClient(transport=transport) - - - """ - def pre_batch_process_documents(self, request: document_processor_service.BatchProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.BatchProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_batch_process_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_create_processor(self, request: document_processor_service.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.CreateProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_create_processor(self, response: gcd_processor.Processor) -> gcd_processor.Processor: - """Post-rpc interceptor for create_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor(self, request: document_processor_service.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor_version(self, request: document_processor_service.DeleteProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_deploy_processor_version(self, request: document_processor_service.DeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_deploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_disable_processor(self, request: document_processor_service.DisableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DisableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for disable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_disable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for disable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_enable_processor(self, request: document_processor_service.EnableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EnableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for enable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_enable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for enable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_evaluate_processor_version(self, request: document_processor_service.EvaluateProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EvaluateProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_evaluate_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_fetch_processor_types(self, request: document_processor_service.FetchProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.FetchProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_fetch_processor_types(self, response: document_processor_service.FetchProcessorTypesResponse) -> document_processor_service.FetchProcessorTypesResponse: - """Post-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_evaluation(self, request: document_processor_service.GetEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_evaluation(self, response: evaluation.Evaluation) -> evaluation.Evaluation: - """Post-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor(self, request: document_processor_service.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor(self, response: processor.Processor) -> processor.Processor: - """Post-rpc interceptor for get_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_type(self, request: document_processor_service.GetProcessorTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_type(self, response: processor_type.ProcessorType) -> processor_type.ProcessorType: - """Post-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_version(self, request: document_processor_service.GetProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_version(self, response: processor.ProcessorVersion) -> processor.ProcessorVersion: - """Post-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_evaluations(self, request: document_processor_service.ListEvaluationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_evaluations(self, response: document_processor_service.ListEvaluationsResponse) -> document_processor_service.ListEvaluationsResponse: - """Post-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processors(self, request: document_processor_service.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processors - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processors(self, response: document_processor_service.ListProcessorsResponse) -> document_processor_service.ListProcessorsResponse: - """Post-rpc interceptor for list_processors - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_types(self, request: document_processor_service.ListProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_types(self, response: document_processor_service.ListProcessorTypesResponse) -> document_processor_service.ListProcessorTypesResponse: - """Post-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_versions(self, request: document_processor_service.ListProcessorVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_versions(self, response: document_processor_service.ListProcessorVersionsResponse) -> document_processor_service.ListProcessorVersionsResponse: - """Post-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_process_document(self, request: document_processor_service.ProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for process_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_process_document(self, response: document_processor_service.ProcessResponse) -> document_processor_service.ProcessResponse: - """Post-rpc interceptor for process_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_review_document(self, request: document_processor_service.ReviewDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ReviewDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for review_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_review_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for review_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_set_default_processor_version(self, request: document_processor_service.SetDefaultProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.SetDefaultProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_set_default_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_train_processor_version(self, request: document_processor_service.TrainProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.TrainProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_train_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_undeploy_processor_version(self, request: document_processor_service.UndeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.UndeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_undeploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - def pre_get_location(self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.Location: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_location(self, response: locations_pb2.GetLocationRequest) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_locations(self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.ListLocationsResponse: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_locations(self, response: locations_pb2.ListLocationsRequest) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_cancel_operation(self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]]) -> None: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_cancel_operation(self, response: operations_pb2.CancelOperationRequest) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_operation(self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.Operation: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_operation(self, response: operations_pb2.GetOperationRequest) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_operations(self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.ListOperationsResponse: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_operations(self, response: operations_pb2.ListOperationsRequest) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentProcessorServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentProcessorServiceRestInterceptor - - -class DocumentProcessorServiceRestTransport(DocumentProcessorServiceTransport): - """REST backend transport for DocumentProcessorService. - - Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DocumentProcessorServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentProcessorServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchProcessDocuments(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("BatchProcessDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.BatchProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch process documents method over HTTP. - - Args: - request (~.document_processor_service.BatchProcessRequest): - The request object. Request message for batch process - document method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:batchProcess', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:batchProcess', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_process_documents(request, metadata) - pb_request = document_processor_service.BatchProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_process_documents(resp) - return resp - - class _CreateProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("CreateProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.CreateProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_processor.Processor: - r"""Call the create processor method over HTTP. - - Args: - request (~.document_processor_service.CreateProcessorRequest): - The request object. Request message for create a - processor. Notice this request is sent - to a regionalized backend service, and - if the processor type is not available - on that region, the creation will fail. - - 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: - ~.gcd_processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/processors', - 'body': 'processor', - }, - ] - request, metadata = self._interceptor.pre_create_processor(request, metadata) - pb_request = document_processor_service.CreateProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_processor.Processor() - pb_resp = gcd_processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_processor(resp) - return resp - - class _DeleteProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorRequest): - The request object. Request message for the delete - processor method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor(request, metadata) - pb_request = document_processor_service.DeleteProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor(resp) - return resp - - class _DeleteProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor version method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorVersionRequest): - The request object. Request message for the delete - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor_version(request, metadata) - pb_request = document_processor_service.DeleteProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor_version(resp) - return resp - - class _DeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the deploy processor version method over HTTP. - - Args: - request (~.document_processor_service.DeployProcessorVersionRequest): - The request object. Request message for the deploy - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_deploy_processor_version(request, metadata) - pb_request = document_processor_service.DeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_deploy_processor_version(resp) - return resp - - class _DisableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DisableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DisableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the disable processor method over HTTP. - - Args: - request (~.document_processor_service.DisableProcessorRequest): - The request object. Request message for the disable - processor method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:disable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_disable_processor(request, metadata) - pb_request = document_processor_service.DisableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_disable_processor(resp) - return resp - - class _EnableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EnableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EnableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the enable processor method over HTTP. - - Args: - request (~.document_processor_service.EnableProcessorRequest): - The request object. Request message for the enable - processor method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:enable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_enable_processor(request, metadata) - pb_request = document_processor_service.EnableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_enable_processor(resp) - return resp - - class _EvaluateProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EvaluateProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EvaluateProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the evaluate processor - version method over HTTP. - - Args: - request (~.document_processor_service.EvaluateProcessorVersionRequest): - The request object. Evaluates the given ProcessorVersion - against the supplied documents. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_evaluate_processor_version(request, metadata) - pb_request = document_processor_service.EvaluateProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_evaluate_processor_version(resp) - return resp - - class _FetchProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("FetchProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.FetchProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Call the fetch processor types method over HTTP. - - Args: - request (~.document_processor_service.FetchProcessorTypesRequest): - The request object. Request message for fetch processor - types. - - 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: - ~.document_processor_service.FetchProcessorTypesResponse: - Response message for fetch processor - types. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}:fetchProcessorTypes', - }, - ] - request, metadata = self._interceptor.pre_fetch_processor_types(request, metadata) - pb_request = document_processor_service.FetchProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.FetchProcessorTypesResponse() - pb_resp = document_processor_service.FetchProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_processor_types(resp) - return resp - - class _GetEvaluation(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetEvaluation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetEvaluationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> evaluation.Evaluation: - r"""Call the get evaluation method over HTTP. - - Args: - request (~.document_processor_service.GetEvaluationRequest): - The request object. Retrieves a specific Evaluation. - 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: - ~.evaluation.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_evaluation(request, metadata) - pb_request = document_processor_service.GetEvaluationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = evaluation.Evaluation() - pb_resp = evaluation.Evaluation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_evaluation(resp) - return resp - - class _GetProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.Processor: - r"""Call the get processor method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorRequest): - The request object. Request message for get processor. - 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: - ~.processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor(request, metadata) - pb_request = document_processor_service.GetProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.Processor() - pb_resp = processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor(resp) - return resp - - class _GetProcessorType(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor_type.ProcessorType: - r"""Call the get processor type method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorTypeRequest): - The request object. Request message for get processor. - 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: - ~.processor_type.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processorTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_type(request, metadata) - pb_request = document_processor_service.GetProcessorTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor_type.ProcessorType() - pb_resp = processor_type.ProcessorType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_type(resp) - return resp - - class _GetProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.ProcessorVersion: - r"""Call the get processor version method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorVersionRequest): - The request object. Request message for get processor - version. - - 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: - ~.processor.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pre-trained by Google internally or - up-trained by the customer. At a time, a - processor can only have one default - version version. So the processor's - behavior (when processing documents) is - defined by a default version - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_version(request, metadata) - pb_request = document_processor_service.GetProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.ProcessorVersion() - pb_resp = processor.ProcessorVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_version(resp) - return resp - - class _ListEvaluations(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListEvaluations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListEvaluationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListEvaluationsResponse: - r"""Call the list evaluations method over HTTP. - - Args: - request (~.document_processor_service.ListEvaluationsRequest): - The request object. Retrieves a list of evaluations for a - given ProcessorVersion. - - 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: - ~.document_processor_service.ListEvaluationsResponse: - The response from ListEvaluations. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations', - }, - ] - request, metadata = self._interceptor.pre_list_evaluations(request, metadata) - pb_request = document_processor_service.ListEvaluationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListEvaluationsResponse() - pb_resp = document_processor_service.ListEvaluationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_evaluations(resp) - return resp - - class _ListProcessors(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessors") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorsResponse: - r"""Call the list processors method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorsRequest): - The request object. Request message for list all - processors belongs to a project. - - 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: - ~.document_processor_service.ListProcessorsResponse: - Response message for list processors. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/processors', - }, - ] - request, metadata = self._interceptor.pre_list_processors(request, metadata) - pb_request = document_processor_service.ListProcessorsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorsResponse() - pb_resp = document_processor_service.ListProcessorsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processors(resp) - return resp - - class _ListProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorTypesResponse: - r"""Call the list processor types method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorTypesRequest): - The request object. Request message for list processor - types. - - 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: - ~.document_processor_service.ListProcessorTypesResponse: - Response message for list processor - types. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/processorTypes', - }, - ] - request, metadata = self._interceptor.pre_list_processor_types(request, metadata) - pb_request = document_processor_service.ListProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorTypesResponse() - pb_resp = document_processor_service.ListProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_types(resp) - return resp - - class _ListProcessorVersions(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorVersionsResponse: - r"""Call the list processor versions method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorVersionsRequest): - The request object. Request message for list all - processor versions belongs to a - processor. - - 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: - ~.document_processor_service.ListProcessorVersionsResponse: - Response message for list processors. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/processors/*}/processorVersions', - }, - ] - request, metadata = self._interceptor.pre_list_processor_versions(request, metadata) - pb_request = document_processor_service.ListProcessorVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorVersionsResponse() - pb_resp = document_processor_service.ListProcessorVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_versions(resp) - return resp - - class _ProcessDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ProcessDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ProcessResponse: - r"""Call the process document method over HTTP. - - Args: - request (~.document_processor_service.ProcessRequest): - The request object. Request message for the process - document method. - - 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: - ~.document_processor_service.ProcessResponse: - Response message for the process - document method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:process', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:process', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_process_document(request, metadata) - pb_request = document_processor_service.ProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ProcessResponse() - pb_resp = document_processor_service.ProcessResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_process_document(resp) - return resp - - class _ReviewDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ReviewDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ReviewDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the review document method over HTTP. - - Args: - request (~.document_processor_service.ReviewDocumentRequest): - The request object. Request message for review document - method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_review_document(request, metadata) - pb_request = document_processor_service.ReviewDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_review_document(resp) - return resp - - class _SetDefaultProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("SetDefaultProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.SetDefaultProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the set default processor - version method over HTTP. - - Args: - request (~.document_processor_service.SetDefaultProcessorVersionRequest): - The request object. Request message for the set default - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{processor=projects/*/locations/*/processors/*}:setDefaultProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_default_processor_version(request, metadata) - pb_request = document_processor_service.SetDefaultProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_default_processor_version(resp) - return resp - - class _TrainProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("TrainProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.TrainProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the train processor version method over HTTP. - - Args: - request (~.document_processor_service.TrainProcessorVersionRequest): - The request object. Request message for the create - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_train_processor_version(request, metadata) - pb_request = document_processor_service.TrainProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_train_processor_version(resp) - return resp - - class _UndeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("UndeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.UndeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the undeploy processor - version method over HTTP. - - Args: - request (~.document_processor_service.UndeployProcessorVersionRequest): - The request object. Request message for the undeploy - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_undeploy_processor_version(request, metadata) - pb_request = document_processor_service.UndeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_undeploy_processor_version(resp) - return resp - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchProcessDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DisableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EnableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EvaluateProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._FetchProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - evaluation.Evaluation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - document_processor_service.ListEvaluationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ProcessDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ReviewDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetDefaultProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TrainProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UndeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentProcessorServiceRestTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py deleted file mode 100644 index b86d11cb..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py +++ /dev/null @@ -1,172 +0,0 @@ -# -*- 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 .barcode import ( - Barcode, -) -from .document import ( - Document, -) -from .document_io import ( - BatchDocumentsInputConfig, - DocumentOutputConfig, - GcsDocument, - GcsDocuments, - GcsPrefix, - RawDocument, -) -from .document_processor_service import ( - BatchProcessMetadata, - BatchProcessRequest, - BatchProcessResponse, - CreateProcessorRequest, - DeleteProcessorMetadata, - DeleteProcessorRequest, - DeleteProcessorVersionMetadata, - DeleteProcessorVersionRequest, - DeployProcessorVersionMetadata, - DeployProcessorVersionRequest, - DeployProcessorVersionResponse, - DisableProcessorMetadata, - DisableProcessorRequest, - DisableProcessorResponse, - EnableProcessorMetadata, - EnableProcessorRequest, - EnableProcessorResponse, - EvaluateProcessorVersionMetadata, - EvaluateProcessorVersionRequest, - EvaluateProcessorVersionResponse, - FetchProcessorTypesRequest, - FetchProcessorTypesResponse, - GetEvaluationRequest, - GetProcessorRequest, - GetProcessorTypeRequest, - GetProcessorVersionRequest, - HumanReviewStatus, - ListEvaluationsRequest, - ListEvaluationsResponse, - ListProcessorsRequest, - ListProcessorsResponse, - ListProcessorTypesRequest, - ListProcessorTypesResponse, - ListProcessorVersionsRequest, - ListProcessorVersionsResponse, - ProcessRequest, - ProcessResponse, - ReviewDocumentOperationMetadata, - ReviewDocumentRequest, - ReviewDocumentResponse, - SetDefaultProcessorVersionMetadata, - SetDefaultProcessorVersionRequest, - SetDefaultProcessorVersionResponse, - TrainProcessorVersionMetadata, - TrainProcessorVersionRequest, - TrainProcessorVersionResponse, - UndeployProcessorVersionMetadata, - UndeployProcessorVersionRequest, - UndeployProcessorVersionResponse, -) -from .document_schema import ( - DocumentSchema, -) -from .evaluation import ( - Evaluation, - EvaluationReference, -) -from .geometry import ( - BoundingPoly, - NormalizedVertex, - Vertex, -) -from .operation_metadata import ( - CommonOperationMetadata, -) -from .processor import ( - Processor, - ProcessorVersion, -) -from .processor_type import ( - ProcessorType, -) - -__all__ = ( - 'Barcode', - 'Document', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorType', -) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py deleted file mode 100644 index 3e7ca5bd..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- 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 - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'Barcode', - }, -) - - -class Barcode(proto.Message): - r"""Encodes the detailed information of a barcode. - - 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. - 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. - raw_value (str): - Raw value encoded in the barcode. For example: - ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. - """ - - format_: str = proto.Field( - proto.STRING, - number=1, - ) - value_format: str = proto.Field( - proto.STRING, - number=2, - ) - raw_value: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py deleted file mode 100644 index 131d383f..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py +++ /dev/null @@ -1,1708 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.cloud.documentai_v1.types import barcode as gcd_barcode -from google.cloud.documentai_v1.types import geometry -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import color_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import money_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'Document', - }, -) - - -class Document(proto.Message): - r"""Document represents the canonical document resource in - Document AI. It is an interchange format that provides insights - into documents and allows for collaboration between users and - Document AI to iterate and optimize for quality. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - uri (str): - Optional. Currently supports Google Cloud Storage URI of the - form ``gs://bucket_name/object_name``. Object versioning is - not supported. See `Google Cloud Storage Request - URIs `__ - for more info. - - This field is a member of `oneof`_ ``source``. - content (bytes): - Optional. Inline document content, represented as a stream - of bytes. Note: As with all ``bytes`` fields, protobuffers - use a pure binary representation, whereas JSON - representations use base64. - - This field is a member of `oneof`_ ``source``. - mime_type (str): - An IANA published MIME type (also referred to - as media type). For more information, see - https://www.iana.org/assignments/media-types/media-types.xhtml. - text (str): - Optional. UTF-8 encoded text in reading order - from the document. - text_styles (MutableSequence[google.cloud.documentai_v1.types.Document.Style]): - Styles for the - [Document.text][google.cloud.documentai.v1.Document.text]. - pages (MutableSequence[google.cloud.documentai_v1.types.Document.Page]): - Visual page layout for the - [Document][google.cloud.documentai.v1.Document]. - entities (MutableSequence[google.cloud.documentai_v1.types.Document.Entity]): - A list of entities detected on - [Document.text][google.cloud.documentai.v1.Document.text]. - For document shards, entities in this list may cross shard - boundaries. - entity_relations (MutableSequence[google.cloud.documentai_v1.types.Document.EntityRelation]): - Placeholder. Relationship among - [Document.entities][google.cloud.documentai.v1.Document.entities]. - text_changes (MutableSequence[google.cloud.documentai_v1.types.Document.TextChange]): - Placeholder. A list of text corrections made to - [Document.text][google.cloud.documentai.v1.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_v1.types.Document.ShardInfo): - Information about the sharding if this - document is sharded part of a larger document. - If the document is not sharded, this message is - not specified. - error (google.rpc.status_pb2.Status): - Any error that occurred while processing this - document. - revisions (MutableSequence[google.cloud.documentai_v1.types.Document.Revision]): - Placeholder. Revision history of this - document. - """ - - class ShardInfo(proto.Message): - r"""For a large document, sharding may be performed to produce - several document shards. Each document shard contains this field - to detail which shard it is. - - Attributes: - shard_index (int): - The 0-based index of this shard. - shard_count (int): - Total number of shards. - text_offset (int): - The index of the first character in - [Document.text][google.cloud.documentai.v1.Document.text] in - the overall document global text. - """ - - shard_index: int = proto.Field( - proto.INT64, - number=1, - ) - shard_count: int = proto.Field( - proto.INT64, - number=2, - ) - text_offset: int = proto.Field( - proto.INT64, - number=3, - ) - - class Style(proto.Message): - r"""Annotation for common text style attributes. This adheres to - CSS conventions as much as possible. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - color (google.type.color_pb2.Color): - Text color. - background_color (google.type.color_pb2.Color): - Text background color. - font_weight (str): - Font weight. Possible values are normal, bold, bolder, and - lighter. https://www.w3schools.com/cssref/pr_font_weight.asp - text_style (str): - Text style. Possible values are normal, italic, and oblique. - https://www.w3schools.com/cssref/pr_font_font-style.asp - text_decoration (str): - Text decoration. Follows CSS standard. - https://www.w3schools.com/cssref/pr_text_text-decoration.asp - font_size (google.cloud.documentai_v1.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): - r"""Font size with unit. - - Attributes: - size (float): - Font size for the text. - unit (str): - Unit for the font size. Follows CSS naming - (in, px, pt, etc.). - """ - - size: float = proto.Field( - proto.FLOAT, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=2, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=3, - message=color_pb2.Color, - ) - font_weight: str = proto.Field( - proto.STRING, - number=4, - ) - text_style: str = proto.Field( - proto.STRING, - number=5, - ) - text_decoration: str = proto.Field( - proto.STRING, - number=6, - ) - font_size: 'Document.Style.FontSize' = proto.Field( - 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.v1.Document]. - - Attributes: - page_number (int): - 1-based index for current - [Page][google.cloud.documentai.v1.Document.Page] in a parent - [Document][google.cloud.documentai.v1.Document]. Useful when - a page is taken out of a - [Document][google.cloud.documentai.v1.Document] for - individual processing. - image (google.cloud.documentai_v1.types.Document.Page.Image): - Rendered image for this page. This image is - preprocessed to remove any skew, rotation, and - distortions such that the annotation bounding - boxes can be upright and axis-aligned. - transforms (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Matrix]): - Transformation matrices that were applied to the original - document image to produce - [Page.image][google.cloud.documentai.v1.Document.Page.image]. - dimension (google.cloud.documentai_v1.types.Document.Page.Dimension): - Physical dimension of the page. - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for the page. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - blocks (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Block]): - A list of visually detected text blocks on - the page. A block has a set of lines (collected - into paragraphs) that have a common line-spacing - and orientation. - paragraphs (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Paragraph]): - A list of visually detected text paragraphs - on the page. A collection of lines that a human - would perceive as a paragraph. - lines (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Line]): - A list of visually detected text lines on the - page. A collection of tokens that a human would - perceive as a line. - tokens (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Token]): - A list of visually detected tokens on the - page. - visual_elements (MutableSequence[google.cloud.documentai_v1.types.Document.Page.VisualElement]): - A list of detected non-text visual elements - e.g. checkbox, signature etc. on the page. - tables (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table]): - A list of visually detected tables on the - page. - form_fields (MutableSequence[google.cloud.documentai_v1.types.Document.Page.FormField]): - A list of visually detected form fields on - the page. - symbols (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Symbol]): - A list of visually detected symbols on the - page. - detected_barcodes (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedBarcode]): - A list of detected barcodes. - image_quality_scores (google.cloud.documentai_v1.types.Document.Page.ImageQualityScores): - Image Quality Scores. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this page. - """ - - class Dimension(proto.Message): - r"""Dimension for the page. - - Attributes: - width (float): - Page width. - height (float): - Page height. - unit (str): - Dimension unit. - """ - - width: float = proto.Field( - proto.FLOAT, - number=1, - ) - height: float = proto.Field( - proto.FLOAT, - number=2, - ) - unit: str = proto.Field( - proto.STRING, - number=3, - ) - - class Image(proto.Message): - r"""Rendered image contents for this page. - - Attributes: - content (bytes): - Raw byte content of the image. - mime_type (str): - Encoding mime type for the image. - width (int): - Width of the image in pixels. - height (int): - Height of the image in pixels. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - width: int = proto.Field( - proto.INT32, - number=3, - ) - height: int = proto.Field( - proto.INT32, - number=4, - ) - - class Matrix(proto.Message): - r"""Representation for transformation matrix, intended to be - compatible and used with OpenCV format for image manipulation. - - Attributes: - rows (int): - Number of rows in the matrix. - cols (int): - Number of columns in the matrix. - type_ (int): - This encodes information about what data type the matrix - uses. For example, 0 (CV_8U) is an unsigned 8-bit image. For - the full list of OpenCV primitive data types, please refer - to - https://docs.opencv.org/4.3.0/d1/d1b/group__core__hal__interface.html - data (bytes): - The matrix data. - """ - - rows: int = proto.Field( - proto.INT32, - number=1, - ) - cols: int = proto.Field( - proto.INT32, - number=2, - ) - type_: int = proto.Field( - proto.INT32, - number=3, - ) - data: bytes = proto.Field( - proto.BYTES, - number=4, - ) - - class Layout(proto.Message): - r"""Visual element describing a layout unit on a page. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - confidence (float): - Confidence of the current - [Layout][google.cloud.documentai.v1.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]``. - bounding_poly (google.cloud.documentai_v1.types.BoundingPoly): - The bounding polygon for the - [Layout][google.cloud.documentai.v1.Document.Page.Layout]. - orientation (google.cloud.documentai_v1.types.Document.Page.Layout.Orientation): - Detected orientation for the - [Layout][google.cloud.documentai.v1.Document.Page.Layout]. - """ - class Orientation(proto.Enum): - r"""Detected human reading orientation. - - Values: - ORIENTATION_UNSPECIFIED (0): - Unspecified orientation. - PAGE_UP (1): - Orientation is aligned with page up. - PAGE_RIGHT (2): - Orientation is aligned with page right. - Turn the head 90 degrees clockwise from upright - to read. - PAGE_DOWN (3): - Orientation is aligned with page down. - Turn the head 180 degrees from upright to read. - PAGE_LEFT (4): - Orientation is aligned with page left. - Turn the head 90 degrees counterclockwise from - upright to read. - """ - ORIENTATION_UNSPECIFIED = 0 - PAGE_UP = 1 - PAGE_RIGHT = 2 - PAGE_DOWN = 3 - PAGE_LEFT = 4 - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=3, - message=geometry.BoundingPoly, - ) - orientation: 'Document.Page.Layout.Orientation' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Page.Layout.Orientation', - ) - - class Block(proto.Message): - r"""A block has a set of lines (collected into paragraphs) that - have a common line-spacing and orientation. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Block][google.cloud.documentai.v1.Document.Page.Block]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Paragraph(proto.Message): - r"""A collection of lines that a human would perceive as a - paragraph. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [Paragraph][google.cloud.documentai.v1.Document.Page.Paragraph]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Line(proto.Message): - r"""A collection of tokens that a human would perceive as a line. - Does not cross column boundaries, can be horizontal, vertical, - etc. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Line][google.cloud.documentai.v1.Document.Page.Line]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Token(proto.Message): - r"""A detected token. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Token][google.cloud.documentai.v1.Document.Page.Token]. - detected_break (google.cloud.documentai_v1.types.Document.Page.Token.DetectedBreak): - Detected break at the end of a - [Token][google.cloud.documentai.v1.Document.Page.Token]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - class DetectedBreak(proto.Message): - r"""Detected break at the end of a - [Token][google.cloud.documentai.v1.Document.Page.Token]. - - Attributes: - type_ (google.cloud.documentai_v1.types.Document.Page.Token.DetectedBreak.Type): - Detected break type. - """ - class Type(proto.Enum): - r"""Enum to denote the type of break found. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified break type. - SPACE (1): - A single whitespace. - WIDE_SPACE (2): - A wider whitespace. - HYPHEN (3): - A hyphen that indicates that a token has been - split across lines. - """ - TYPE_UNSPECIFIED = 0 - SPACE = 1 - WIDE_SPACE = 2 - HYPHEN = 3 - - type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Document.Page.Token.DetectedBreak.Type', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Token.DetectedBreak', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=4, - message='Document.Provenance', - ) - - class Symbol(proto.Message): - r"""A detected symbol. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [Symbol][google.cloud.documentai.v1.Document.Page.Symbol]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class VisualElement(proto.Message): - r"""Detected non-text visual elements e.g. checkbox, signature - etc. on the page. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [VisualElement][google.cloud.documentai.v1.Document.Page.VisualElement]. - type_ (str): - Type of the - [VisualElement][google.cloud.documentai.v1.Document.Page.VisualElement]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - - class Table(proto.Message): - r"""A table representation similar to HTML table structure. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Table][google.cloud.documentai.v1.Document.Page.Table]. - header_rows (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): - Header rows of the table. - body_rows (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): - Body rows of the table. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this table. - """ - - class TableRow(proto.Message): - r"""A row of table cells. - - Attributes: - cells (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableCell]): - Cells that make up this row. - """ - - cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.Page.Table.TableCell', - ) - - class TableCell(proto.Message): - r"""A cell representation inside the table. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [TableCell][google.cloud.documentai.v1.Document.Page.Table.TableCell]. - row_span (int): - How many rows this cell spans. - col_span (int): - How many columns this cell spans. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - row_span: int = proto.Field( - proto.INT32, - number=2, - ) - col_span: int = proto.Field( - proto.INT32, - number=3, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.Table.TableRow', - ) - body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.Table.TableRow', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - 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. - - Attributes: - field_name (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1.Document.Page.FormField] - name. e.g. ``Address``, ``Email``, ``Grand total``, - ``Phone number``, etc. - field_value (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1.Document.Page.FormField] - value. - name_detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages for name - together with confidence. - value_detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages for value - together with confidence. - value_type (str): - If the value is non-textual, this field represents the type. - Current valid values are: - - - blank (this indicates the ``field_value`` is normal text) - - ``unfilled_checkbox`` - - ``filled_checkbox`` - corrected_key_text (str): - Created for Labeling UI to export key text. If corrections - were made to the text identified by the - ``field_name.text_anchor``, this field will contain the - correction. - corrected_value_text (str): - Created for Labeling UI to export value text. If corrections - were made to the text identified by the - ``field_value.text_anchor``, this field will contain the - correction. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - field_name: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - field_value: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Layout', - ) - name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - value_type: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_key_text: str = proto.Field( - proto.STRING, - number=6, - ) - corrected_value_text: str = proto.Field( - proto.STRING, - number=7, - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=8, - message='Document.Provenance', - ) - - class DetectedBarcode(proto.Message): - r"""A detected barcode. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [DetectedBarcode][google.cloud.documentai.v1.Document.Page.DetectedBarcode]. - barcode (google.cloud.documentai_v1.types.Barcode): - Detailed barcode information of the - [DetectedBarcode][google.cloud.documentai.v1.Document.Page.DetectedBarcode]. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - barcode: gcd_barcode.Barcode = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_barcode.Barcode, - ) - - class DetectedLanguage(proto.Message): - r"""Detected language for a structural component. - - Attributes: - language_code (str): - 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]``. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - 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_v1.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, - ) - image: 'Document.Page.Image' = proto.Field( - proto.MESSAGE, - number=13, - message='Document.Page.Image', - ) - transforms: MutableSequence['Document.Page.Matrix'] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='Document.Page.Matrix', - ) - dimension: 'Document.Page.Dimension' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Dimension', - ) - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Document.Page.Block', - ) - paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Document.Page.Paragraph', - ) - lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Document.Page.Line', - ) - tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='Document.Page.Token', - ) - visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Document.Page.VisualElement', - ) - tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Page.Table', - ) - form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='Document.Page.FormField', - ) - symbols: MutableSequence['Document.Page.Symbol'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='Document.Page.Symbol', - ) - detected_barcodes: MutableSequence['Document.Page.DetectedBarcode'] = proto.RepeatedField( - 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, - message='Document.Provenance', - ) - - class Entity(proto.Message): - r"""An entity that could be a phrase in the text or a property - that belongs to the document. It is a known entity type, such as - a person, an organization, or location. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Optional. Provenance of the entity. Text anchor indexing - into the - [Document.text][google.cloud.documentai.v1.Document.text]. - type_ (str): - Required. Entity type from a schema e.g. ``Address``. - mention_text (str): - 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]``. - page_anchor (google.cloud.documentai_v1.types.Document.PageAnchor): - Optional. Represents the provenance of this - entity wrt. the location on the page where it - was found. - id (str): - Optional. Canonical id. This will be a unique - value in the entity list for this document. - normalized_value (google.cloud.documentai_v1.types.Document.Entity.NormalizedValue): - Optional. Normalized entity value. Absent if - the extracted value could not be converted or - the type (e.g. address) is not supported for - certain parsers. This field is also only - populated for certain supported document types. - properties (MutableSequence[google.cloud.documentai_v1.types.Document.Entity]): - Optional. Entities can be nested to form a - hierarchical data structure representing the - content in the document. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - Optional. The history of this annotation. - redacted (bool): - Optional. Whether the entity will be redacted - for de-identification purposes. - """ - - class NormalizedValue(proto.Message): - r"""Parsed and normalized entity value. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - money_value (google.type.money_pb2.Money): - Money value. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/money.proto - - This field is a member of `oneof`_ ``structured_value``. - date_value (google.type.date_pb2.Date): - Date value. Includes year, month, day. See - also: - https://github.com/googleapis/googleapis/blob/master/google/type/date.proto - - This field is a member of `oneof`_ ``structured_value``. - datetime_value (google.type.datetime_pb2.DateTime): - DateTime value. Includes date, time, and - timezone. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/datetime.proto - - This field is a member of `oneof`_ ``structured_value``. - address_value (google.type.postal_address_pb2.PostalAddress): - Postal address. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/postal_address.proto - - This field is a member of `oneof`_ ``structured_value``. - boolean_value (bool): - Boolean value. Can be used for entities with - binary values, or for checkboxes. - - This field is a member of `oneof`_ ``structured_value``. - integer_value (int): - Integer value. - - This field is a member of `oneof`_ ``structured_value``. - float_value (float): - Float value. - - This field is a member of `oneof`_ ``structured_value``. - text (str): - Optional. An optional field to store a normalized string. - For some entity types, one of respective - ``structured_value`` fields may also be populated. Also not - all the types of ``structured_value`` will be normalized. - For example, some processors may not generate ``float`` or - ``integer`` normalized text by default. - - Below are sample formats mapped to structured values. - - - Money/Currency type (``money_value``) is in the ISO 4217 - text format. - - Date type (``date_value``) is in the ISO 8601 text - format. - - Datetime type (``datetime_value``) is in the ISO 8601 - text format. - """ - - money_value: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - oneof='structured_value', - message=money_pb2.Money, - ) - date_value: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - oneof='structured_value', - message=date_pb2.Date, - ) - datetime_value: datetime_pb2.DateTime = proto.Field( - proto.MESSAGE, - number=4, - oneof='structured_value', - message=datetime_pb2.DateTime, - ) - address_value: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=5, - oneof='structured_value', - message=postal_address_pb2.PostalAddress, - ) - boolean_value: bool = proto.Field( - proto.BOOL, - number=6, - oneof='structured_value', - ) - integer_value: int = proto.Field( - proto.INT32, - number=7, - oneof='structured_value', - ) - float_value: float = proto.Field( - proto.FLOAT, - number=8, - oneof='structured_value', - ) - text: str = proto.Field( - proto.STRING, - number=1, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - mention_text: str = proto.Field( - proto.STRING, - number=3, - ) - mention_id: str = proto.Field( - proto.STRING, - number=4, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - page_anchor: 'Document.PageAnchor' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.PageAnchor', - ) - id: str = proto.Field( - proto.STRING, - number=7, - ) - normalized_value: 'Document.Entity.NormalizedValue' = proto.Field( - proto.MESSAGE, - number=9, - message='Document.Entity.NormalizedValue', - ) - properties: MutableSequence['Document.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Entity', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=11, - message='Document.Provenance', - ) - redacted: bool = proto.Field( - proto.BOOL, - number=12, - ) - - class EntityRelation(proto.Message): - r"""Relationship between - [Entities][google.cloud.documentai.v1.Document.Entity]. - - Attributes: - subject_id (str): - Subject entity id. - object_id (str): - Object entity id. - relation (str): - Relationship description. - """ - - subject_id: str = proto.Field( - proto.STRING, - number=1, - ) - object_id: str = proto.Field( - proto.STRING, - number=2, - ) - relation: str = proto.Field( - proto.STRING, - number=3, - ) - - class TextAnchor(proto.Message): - r"""Text reference indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - - Attributes: - text_segments (MutableSequence[google.cloud.documentai_v1.types.Document.TextAnchor.TextSegment]): - The text segments from the - [Document.text][google.cloud.documentai.v1.Document.text]. - content (str): - Contains the content of the text span so that users do not - have to look it up in the text_segments. It is always - populated for formFields. - """ - - class TextSegment(proto.Message): - r"""A text segment in the - [Document.text][google.cloud.documentai.v1.Document.text]. The - indices may be out of bounds which indicate that the text extends - into another document shard for large sharded documents. See - [ShardInfo.text_offset][google.cloud.documentai.v1.Document.ShardInfo.text_offset] - - Attributes: - start_index (int): - [TextSegment][google.cloud.documentai.v1.Document.TextAnchor.TextSegment] - start UTF-8 char index in the - [Document.text][google.cloud.documentai.v1.Document.text]. - end_index (int): - [TextSegment][google.cloud.documentai.v1.Document.TextAnchor.TextSegment] - half open end UTF-8 char index in the - [Document.text][google.cloud.documentai.v1.Document.text]. - """ - - start_index: int = proto.Field( - proto.INT64, - number=1, - ) - end_index: int = proto.Field( - proto.INT64, - number=2, - ) - - text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.TextAnchor.TextSegment', - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class PageAnchor(proto.Message): - r"""Referencing the visual context of the entity in the - [Document.pages][google.cloud.documentai.v1.Document.pages]. Page - anchors can be cross-page, consist of multiple bounding polygons and - optionally reference specific layout element types. - - Attributes: - page_refs (MutableSequence[google.cloud.documentai_v1.types.Document.PageAnchor.PageRef]): - One or more references to visual page - elements - """ - - class PageRef(proto.Message): - r"""Represents a weak reference to a page element within a - document. - - Attributes: - page (int): - Required. Index into the - [Document.pages][google.cloud.documentai.v1.Document.pages] - element, for example using - ``[Document.pages][page_refs.page]`` to locate the related - page element. This field is skipped when its value is the - default ``0``. See - https://developers.google.com/protocol-buffers/docs/proto3#json. - layout_type (google.cloud.documentai_v1.types.Document.PageAnchor.PageRef.LayoutType): - Optional. The type of the layout element that - is being referenced if any. - layout_id (str): - Optional. Deprecated. Use - [PageRef.bounding_poly][google.cloud.documentai.v1.Document.PageAnchor.PageRef.bounding_poly] - instead. - bounding_poly (google.cloud.documentai_v1.types.BoundingPoly): - Optional. Identifies the bounding polygon of - a layout element on the page. - confidence (float): - Optional. Confidence of detected page element, if - applicable. Range ``[0, 1]``. - """ - class LayoutType(proto.Enum): - r"""The type of layout that is being referenced. - - Values: - LAYOUT_TYPE_UNSPECIFIED (0): - Layout Unspecified. - BLOCK (1): - References a - [Page.blocks][google.cloud.documentai.v1.Document.Page.blocks] - element. - PARAGRAPH (2): - References a - [Page.paragraphs][google.cloud.documentai.v1.Document.Page.paragraphs] - element. - LINE (3): - References a - [Page.lines][google.cloud.documentai.v1.Document.Page.lines] - element. - TOKEN (4): - References a - [Page.tokens][google.cloud.documentai.v1.Document.Page.tokens] - element. - VISUAL_ELEMENT (5): - References a - [Page.visual_elements][google.cloud.documentai.v1.Document.Page.visual_elements] - element. - TABLE (6): - Refrrences a - [Page.tables][google.cloud.documentai.v1.Document.Page.tables] - element. - FORM_FIELD (7): - References a - [Page.form_fields][google.cloud.documentai.v1.Document.Page.form_fields] - element. - """ - LAYOUT_TYPE_UNSPECIFIED = 0 - BLOCK = 1 - PARAGRAPH = 2 - LINE = 3 - TOKEN = 4 - VISUAL_ELEMENT = 5 - TABLE = 6 - FORM_FIELD = 7 - - page: int = proto.Field( - proto.INT64, - number=1, - ) - layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( - proto.ENUM, - number=2, - enum='Document.PageAnchor.PageRef.LayoutType', - ) - layout_id: str = proto.Field( - proto.STRING, - number=3, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=4, - message=geometry.BoundingPoly, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - - page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.PageAnchor.PageRef', - ) - - class Provenance(proto.Message): - r"""Structure to identify provenance relationships between - annotations in different revisions. - - Attributes: - revision (int): - The index of the revision that produced this - element. - id (int): - The Id of this operation. Needs to be unique - within the scope of the revision. - parents (MutableSequence[google.cloud.documentai_v1.types.Document.Provenance.Parent]): - References to the original elements that are - replaced. - type_ (google.cloud.documentai_v1.types.Document.Provenance.OperationType): - The type of provenance operation. - """ - class OperationType(proto.Enum): - r"""If a processor or agent does an explicit operation on - existing elements. - - Values: - OPERATION_TYPE_UNSPECIFIED (0): - Operation type unspecified. If no operation is specified a - provenance entry is simply used to match against a - ``parent``. - ADD (1): - Add an element. - REMOVE (2): - Remove an element identified by ``parent``. - UPDATE (7): - Updates any fields within the given - provenance scope of the message. It 'overwrites' - the fields rather than replacing them. This is - especially relevant when we just want to update - a field value of an entity without also - affecting all the child properties. - REPLACE (3): - Currently unused. Replace an element identified by - ``parent``. - EVAL_REQUESTED (4): - Deprecated. Request human review for the element identified - by ``parent``. - EVAL_APPROVED (5): - Deprecated. Element is reviewed and approved - at human review, confidence will be set to 1.0. - EVAL_SKIPPED (6): - Deprecated. Element is skipped in the - validation process. - """ - OPERATION_TYPE_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - UPDATE = 7 - REPLACE = 3 - EVAL_REQUESTED = 4 - EVAL_APPROVED = 5 - EVAL_SKIPPED = 6 - - class Parent(proto.Message): - r"""The parent element the current element is based on. Used for - referencing/aligning, removal and replacement operations. - - Attributes: - revision (int): - The index of the index into current revision's parent_ids - list. - index (int): - The index of the parent item in the - corresponding item list (eg. list of entities, - properties within entities, etc.) in the parent - revision. - id (int): - The id of the parent provenance. - """ - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - index: int = proto.Field( - proto.INT32, - number=3, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - parents: MutableSequence['Document.Provenance.Parent'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance.Parent', - ) - type_: 'Document.Provenance.OperationType' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Provenance.OperationType', - ) - - class Revision(proto.Message): - r"""Contains past or forward revisions of this document. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - agent (str): - If the change was made by a person specify - the name or id of that person. - - This field is a member of `oneof`_ ``source``. - processor (str): - If the annotation was made by processor - identify the processor by its resource name. - - This field is a member of `oneof`_ ``source``. - id (str): - Id of the revision, internally generated by - doc proto storage. Unique within the context of - the document. - parent (MutableSequence[int]): - The revisions that this revision is based on. This can - include one or more parent (when documents are merged.) This - field represents the index into the ``revisions`` field. - parent_ids (MutableSequence[str]): - The revisions that this revision is based on. Must include - all the ids that have anything to do with this revision - - eg. there are ``provenance.parent.revision`` fields that - index into this field. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the revision was created, - internally generated by doc proto storage at the - time of create. - human_review (google.cloud.documentai_v1.types.Document.Revision.HumanReview): - Human Review information of this revision. - """ - - class HumanReview(proto.Message): - r"""Human Review information of the document. - - Attributes: - state (str): - Human review state. e.g. ``requested``, ``succeeded``, - ``rejected``. - state_message (str): - A message providing more details about the current state of - processing. For example, the rejection reason when the state - is ``rejected``. - """ - - state: str = proto.Field( - proto.STRING, - number=1, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - - agent: str = proto.Field( - proto.STRING, - number=4, - oneof='source', - ) - processor: str = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - id: str = proto.Field( - proto.STRING, - number=1, - ) - parent: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=2, - ) - parent_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - human_review: 'Document.Revision.HumanReview' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.Revision.HumanReview', - ) - - class TextChange(proto.Message): - r"""This message is used for text changes aka. OCR corrections. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Provenance of the correction. Text anchor indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - There can only be a single ``TextAnchor.text_segments`` - element. If the start and end index of the text segment are - the same, the text change is inserted before that index. - changed_text (str): - The text that replaces the text identified in the - ``text_anchor``. - provenance (MutableSequence[google.cloud.documentai_v1.types.Document.Provenance]): - The history of this annotation. - """ - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - changed_text: str = proto.Field( - proto.STRING, - number=2, - ) - provenance: MutableSequence['Document.Provenance'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - text: str = proto.Field( - proto.STRING, - number=4, - ) - text_styles: MutableSequence[Style] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Style, - ) - pages: MutableSequence[Page] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Page, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Entity, - ) - entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=EntityRelation, - ) - text_changes: MutableSequence[TextChange] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=TextChange, - ) - shard_info: ShardInfo = proto.Field( - proto.MESSAGE, - number=9, - message=ShardInfo, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - revisions: MutableSequence[Revision] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Revision, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py deleted file mode 100644 index ed4912ab..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py +++ /dev/null @@ -1,221 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'RawDocument', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - }, -) - - -class RawDocument(proto.Message): - r"""Payload message of raw document content (bytes). - - Attributes: - content (bytes): - Inline document content. - mime_type (str): - An IANA MIME type (RFC6838) indicating the nature and format - of the - [content][google.cloud.documentai.v1.RawDocument.content]. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GcsDocument(proto.Message): - r"""Specifies a document stored on Cloud Storage. - - Attributes: - gcs_uri (str): - The Cloud Storage object uri. - mime_type (str): - An IANA MIME type (RFC6838) of the content. - """ - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GcsDocuments(proto.Message): - r"""Specifies a set of documents on Cloud Storage. - - Attributes: - documents (MutableSequence[google.cloud.documentai_v1.types.GcsDocument]): - The list of documents. - """ - - documents: MutableSequence['GcsDocument'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GcsDocument', - ) - - -class GcsPrefix(proto.Message): - r"""Specifies all documents on Cloud Storage with a common - prefix. - - Attributes: - gcs_uri_prefix (str): - The URI prefix. - """ - - gcs_uri_prefix: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchDocumentsInputConfig(proto.Message): - r"""The common config to specify a set of documents used as - input. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (google.cloud.documentai_v1.types.GcsPrefix): - The set of documents that match the specified Cloud Storage - ``gcs_prefix``. - - This field is a member of `oneof`_ ``source``. - gcs_documents (google.cloud.documentai_v1.types.GcsDocuments): - The set of documents individually specified - on Cloud Storage. - - This field is a member of `oneof`_ ``source``. - """ - - gcs_prefix: 'GcsPrefix' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsPrefix', - ) - gcs_documents: 'GcsDocuments' = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsDocuments', - ) - - -class DocumentOutputConfig(proto.Message): - r"""Config that controls the output of documents. All documents - will be written as a JSON file. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_output_config (google.cloud.documentai_v1.types.DocumentOutputConfig.GcsOutputConfig): - Output config to write the results to Cloud - Storage. - - This field is a member of `oneof`_ ``destination``. - """ - - class GcsOutputConfig(proto.Message): - r"""The configuration used when outputting documents. - - Attributes: - gcs_uri (str): - The Cloud Storage uri (a directory) of the - output. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies which fields to include in the output documents. - Only supports top level document and pages field so it must - be in the form of ``{document_field_name}`` or - ``pages.{page_field_name}``. - sharding_config (google.cloud.documentai_v1.types.DocumentOutputConfig.GcsOutputConfig.ShardingConfig): - Specifies the sharding config for the output - document. - """ - - class ShardingConfig(proto.Message): - r"""The sharding config for the output document. - - Attributes: - pages_per_shard (int): - The number of pages per shard. - pages_overlap (int): - The number of overlapping pages between - consecutive shards. - """ - - pages_per_shard: int = proto.Field( - proto.INT32, - number=1, - ) - pages_overlap: int = proto.Field( - proto.INT32, - number=2, - ) - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - sharding_config: 'DocumentOutputConfig.GcsOutputConfig.ShardingConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='DocumentOutputConfig.GcsOutputConfig.ShardingConfig', - ) - - gcs_output_config: GcsOutputConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message=GcsOutputConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py deleted file mode 100644 index 2ffbac1e..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py +++ /dev/null @@ -1,1361 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.cloud.documentai_v1.types import document as gcd_document -from google.cloud.documentai_v1.types import document_io -from google.cloud.documentai_v1.types import document_schema as gcd_document_schema -from google.cloud.documentai_v1.types import evaluation as gcd_evaluation -from google.cloud.documentai_v1.types import operation_metadata -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'ProcessRequest', - 'HumanReviewStatus', - 'ProcessResponse', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'BatchProcessMetadata', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'GetProcessorTypeRequest', - 'GetProcessorRequest', - 'GetProcessorVersionRequest', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'DeleteProcessorVersionRequest', - 'DeleteProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'CreateProcessorRequest', - 'DeleteProcessorRequest', - 'DeleteProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EnableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'DisableProcessorMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'SetDefaultProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'ReviewDocumentOperationMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionResponse', - 'GetEvaluationRequest', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - }, -) - - -class ProcessRequest(proto.Message): - r"""Request message for the process document method. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - inline_document (google.cloud.documentai_v1.types.Document): - An inline document proto. - - This field is a member of `oneof`_ ``source``. - raw_document (google.cloud.documentai_v1.types.RawDocument): - A raw document content (bytes). - - This field is a member of `oneof`_ ``source``. - name (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1.Processor] or - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to use for processing. If a - [Processor][google.cloud.documentai.v1.Processor] is - specified, the server will use its [default - version][google.cloud.documentai.v1.Processor.default_processor_version]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - skip_human_review (bool): - 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. 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( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - raw_document: document_io.RawDocument = proto.Field( - proto.MESSAGE, - number=5, - oneof='source', - message=document_io.RawDocument, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=3, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=6, - message=field_mask_pb2.FieldMask, - ) - - -class HumanReviewStatus(proto.Message): - r"""The status of human review on a processed document. - - Attributes: - state (google.cloud.documentai_v1.types.HumanReviewStatus.State): - The state of human review on the processing - request. - state_message (str): - A message providing more details about the - human review state. - human_review_operation (str): - The name of the operation triggered by the processed - document. This field is populated only when the [state] is - [HUMAN_REVIEW_IN_PROGRESS]. It has the same response type - and metadata as the long running operation returned by - [ReviewDocument] method. - """ - class State(proto.Enum): - r"""The final state of human review on a processed document. - - Values: - STATE_UNSPECIFIED (0): - Human review state is unspecified. Most - likely due to an internal error. - SKIPPED (1): - Human review is skipped for the document. - This can happen because human review is not - enabled on the processor or the processing - request has been set to skip this document. - VALIDATION_PASSED (2): - Human review validation is triggered and - passed, so no review is needed. - IN_PROGRESS (3): - Human review validation is triggered and the - document is under review. - ERROR (4): - Some error happened during triggering human review, see the - [state_message] for details. - """ - STATE_UNSPECIFIED = 0 - SKIPPED = 1 - VALIDATION_PASSED = 2 - IN_PROGRESS = 3 - ERROR = 4 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ProcessResponse(proto.Message): - r"""Response message for the process document method. - - Attributes: - document (google.cloud.documentai_v1.types.Document): - The document payload, will populate fields - based on the processor's behavior. - human_review_status (google.cloud.documentai_v1.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='HumanReviewStatus', - ) - - -class BatchProcessRequest(proto.Message): - r"""Request message for batch process document method. - - Attributes: - name (str): - Required. The resource name of - [Processor][google.cloud.documentai.v1.Processor] or - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - input_documents (google.cloud.documentai_v1.types.BatchDocumentsInputConfig): - The input documents for batch process. - document_output_config (google.cloud.documentai_v1.types.DocumentOutputConfig): - The overall output config for batch process. - skip_human_review (bool): - Whether Human Review feature should be - skipped for this request. Default to false. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - input_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=5, - message=document_io.BatchDocumentsInputConfig, - ) - document_output_config: document_io.DocumentOutputConfig = proto.Field( - proto.MESSAGE, - number=6, - message=document_io.DocumentOutputConfig, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class BatchProcessResponse(proto.Message): - r"""Response message for batch process document method. - """ - - -class BatchProcessMetadata(proto.Message): - r"""The long running operation metadata for batch process method. - - Attributes: - state (google.cloud.documentai_v1.types.BatchProcessMetadata.State): - The state of the current batch processing. - state_message (str): - A message providing more details about the - current state of processing. For example, the - error message if the operation is failed. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - individual_process_statuses (MutableSequence[google.cloud.documentai_v1.types.BatchProcessMetadata.IndividualProcessStatus]): - The list of response details of each - document. - """ - class State(proto.Enum): - r"""Possible states of the batch processing operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - WAITING (1): - Request operation is waiting for scheduling. - RUNNING (2): - Request is being processed. - SUCCEEDED (3): - The batch processing completed successfully. - CANCELLING (4): - The batch processing was being cancelled. - CANCELLED (5): - The batch processing was cancelled. - FAILED (6): - The batch processing has failed. - """ - STATE_UNSPECIFIED = 0 - WAITING = 1 - RUNNING = 2 - SUCCEEDED = 3 - CANCELLING = 4 - CANCELLED = 5 - FAILED = 6 - - class IndividualProcessStatus(proto.Message): - r"""The status of a each individual document in the batch - process. - - Attributes: - input_gcs_source (str): - The source of the document, same as the [input_gcs_source] - field in the request when the batch process started. The - batch process is started by take snapshot of that document, - since a user can move or change that document during the - process. - status (google.rpc.status_pb2.Status): - The status processing the document. - output_gcs_destination (str): - The output_gcs_destination (in the request as - ``output_gcs_destination``) of the processed document if it - was successful, otherwise empty. - human_review_status (google.cloud.documentai_v1.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - input_gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - output_gcs_destination: str = proto.Field( - proto.STRING, - number=3, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=5, - message='HumanReviewStatus', - ) - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - individual_process_statuses: MutableSequence[IndividualProcessStatus] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=IndividualProcessStatus, - ) - - -class FetchProcessorTypesRequest(proto.Message): - r"""Request message for fetch processor types. - - Attributes: - parent (str): - Required. The project of processor type to list. The - available processor types may depend on the allow-listing on - projects. Format: - ``projects/{project}/locations/{location}`` - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FetchProcessorTypesResponse(proto.Message): - r"""Response message for fetch processor types. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1.types.ProcessorType]): - The list of processor types. - """ - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - - -class ListProcessorTypesRequest(proto.Message): - r"""Request message for list processor types. - - Attributes: - parent (str): - Required. The location of processor type to list. The - available processor types may depend on the allow-listing on - projects. Format: - ``projects/{project}/locations/{location}`` - page_size (int): - The maximum number of processor types to - return. If unspecified, at most 100 processor - types will be returned. The maximum value is - 500; values above 500 will be coerced to 500. - page_token (str): - Used to retrieve the next page of results, - empty if at the end of the list. - """ - - 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 ListProcessorTypesResponse(proto.Message): - r"""Response message for list processor types. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1.types.ProcessorType]): - The processor types. - next_page_token (str): - Points to the next page, otherwise empty. - """ - - @property - def raw_page(self): - return self - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListProcessorsRequest(proto.Message): - r"""Request message for list all processors belongs to a project. - - Attributes: - parent (str): - Required. The parent (project and location) which owns this - collection of Processors. Format: - ``projects/{project}/locations/{location}`` - page_size (int): - The maximum number of processors to return. - If unspecified, at most 50 processors will be - returned. The maximum value is 100; values above - 100 will be coerced to 100. - page_token (str): - We will return the processors sorted by - creation time. The page token will point to the - next processor. - """ - - 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 ListProcessorsResponse(proto.Message): - r"""Response message for list processors. - - Attributes: - processors (MutableSequence[google.cloud.documentai_v1.types.Processor]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processors: MutableSequence[gcd_processor.Processor] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.Processor, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetProcessorTypeRequest(proto.Message): - r"""Request message for get processor. - - Attributes: - name (str): - Required. The processor type resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorRequest(proto.Message): - r"""Request message for get processor. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorVersionRequest(proto.Message): - r"""Request message for get processor version. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProcessorVersionsRequest(proto.Message): - r"""Request message for list all processor versions belongs to a - processor. - - Attributes: - parent (str): - Required. The parent (project, location and processor) to - list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - page_size (int): - The maximum number of processor versions to - return. If unspecified, at most 10 processor - versions will be returned. The maximum value is - 20; values above 20 will be coerced to 20. - page_token (str): - We will return the processor versions sorted - by creation time. The page token will point to - the next processor version. - """ - - 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 ListProcessorVersionsResponse(proto.Message): - r"""Response message for list processors. - - Attributes: - processor_versions (MutableSequence[google.cloud.documentai_v1.types.ProcessorVersion]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processor_versions: MutableSequence[gcd_processor.ProcessorVersion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.ProcessorVersion, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteProcessorVersionRequest(proto.Message): - r"""Request message for the delete processor version method. - - Attributes: - name (str): - Required. The processor version resource name - to be deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for delete processor - version method. - - Attributes: - common_metadata (google.cloud.documentai_v1.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 DeployProcessorVersionRequest(proto.Message): - r"""Request message for the deploy processor version method. - - Attributes: - name (str): - Required. The processor version resource name - to be deployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeployProcessorVersionResponse(proto.Message): - r"""Response message for the deploy processor version method. - """ - - -class DeployProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for deploy processor - version method. - - Attributes: - common_metadata (google.cloud.documentai_v1.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 UndeployProcessorVersionRequest(proto.Message): - r"""Request message for the undeploy processor version method. - - Attributes: - name (str): - Required. The processor version resource name - to be undeployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeployProcessorVersionResponse(proto.Message): - r"""Response message for the undeploy processor version method. - """ - - -class UndeployProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for the undeploy - processor version method. - - Attributes: - common_metadata (google.cloud.documentai_v1.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 CreateProcessorRequest(proto.Message): - r"""Request message for create a processor. Notice this request - is sent to a regionalized backend service, and if the processor - type is not available on that region, the creation will fail. - - Attributes: - parent (str): - Required. The parent (project and location) under which to - create the processor. Format: - ``projects/{project}/locations/{location}`` - processor (google.cloud.documentai_v1.types.Processor): - Required. The processor to be created, requires - [processor_type] and [display_name] to be set. Also, the - processor is under CMEK if CMEK fields are set. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - processor: gcd_processor.Processor = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_processor.Processor, - ) - - -class DeleteProcessorRequest(proto.Message): - r"""Request message for the delete processor method. - - Attributes: - name (str): - Required. The processor resource name to be - deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorMetadata(proto.Message): - r"""The long running operation metadata for delete processor - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class EnableProcessorRequest(proto.Message): - r"""Request message for the enable processor method. - - Attributes: - name (str): - Required. The processor resource name to be - enabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EnableProcessorResponse(proto.Message): - r"""Response message for the enable processor method. - Intentionally empty proto for adding fields in future. - - """ - - -class EnableProcessorMetadata(proto.Message): - r"""The long running operation metadata for enable processor - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class DisableProcessorRequest(proto.Message): - r"""Request message for the disable processor method. - - Attributes: - name (str): - Required. The processor resource name to be - disabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DisableProcessorResponse(proto.Message): - r"""Response message for the disable processor method. - Intentionally empty proto for adding fields in future. - - """ - - -class DisableProcessorMetadata(proto.Message): - r"""The long running operation metadata for disable processor - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class SetDefaultProcessorVersionRequest(proto.Message): - r"""Request message for the set default processor version method. - - Attributes: - processor (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1.Processor] to change - default version. - default_processor_version (str): - Required. The resource name of child - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to use as default. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{version}`` - """ - - processor: str = proto.Field( - proto.STRING, - number=1, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SetDefaultProcessorVersionResponse(proto.Message): - r"""Response message for set default processor version method. - """ - - -class SetDefaultProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for set default processor - version method. - - Attributes: - common_metadata (google.cloud.documentai_v1.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 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_v1.types.ProcessorVersion): - Required. The processor version to be - created. - document_schema (google.cloud.documentai_v1.types.DocumentSchema): - Optional. The schema the processor version - will be trained with. - input_data (google.cloud.documentai_v1.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_v1.types.BatchDocumentsInputConfig): - The documents used for training the new - version. - test_documents (google.cloud.documentai_v1.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_v1.types.CommonOperationMetadata): - The basic metadata of the long running - operation. - training_dataset_validation (google.cloud.documentai_v1.types.TrainProcessorVersionMetadata.DatasetValidation): - The training dataset validation information. - test_dataset_validation (google.cloud.documentai_v1.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. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - inline_document (google.cloud.documentai_v1.types.Document): - An inline document proto. - - This field is a member of `oneof`_ ``source``. - human_review_config (str): - Required. The resource name of the - HumanReviewConfig that the document will be - reviewed with. - enable_schema_validation (bool): - Whether the validation should be performed on - the ad-hoc review request. - priority (google.cloud.documentai_v1.types.ReviewDocumentRequest.Priority): - The priority of the human review task. - document_schema (google.cloud.documentai_v1.types.DocumentSchema): - The document schema of the human review task. - """ - class Priority(proto.Enum): - r"""The priority level of the human review task. - - Values: - DEFAULT (0): - The default priority level. - URGENT (1): - The urgent priority level. The labeling - manager should allocate labeler resource to the - urgent task queue to respect this priority - level. - """ - DEFAULT = 0 - URGENT = 1 - - inline_document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - human_review_config: str = proto.Field( - proto.STRING, - number=1, - ) - enable_schema_validation: bool = proto.Field( - proto.BOOL, - number=3, - ) - priority: Priority = proto.Field( - proto.ENUM, - number=5, - enum=Priority, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_document_schema.DocumentSchema, - ) - - -class ReviewDocumentResponse(proto.Message): - r"""Response message for review document method. - - Attributes: - gcs_destination (str): - The Cloud Storage uri for the human reviewed - document if the review is succeeded. - state (google.cloud.documentai_v1.types.ReviewDocumentResponse.State): - The state of the review operation. - rejection_reason (str): - The reason why the review is rejected by - reviewer. - """ - class State(proto.Enum): - r"""Possible states of the review operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - REJECTED (1): - The review operation is rejected by the - reviewer. - SUCCEEDED (2): - The review operation is succeeded. - """ - STATE_UNSPECIFIED = 0 - REJECTED = 1 - SUCCEEDED = 2 - - gcs_destination: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - rejection_reason: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ReviewDocumentOperationMetadata(proto.Message): - r"""The long running operation metadata for review document - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long running - operation. - question_id (str): - The Crowd Compute question ID. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - question_id: str = proto.Field( - proto.STRING, - number=6, - ) - - -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.v1.ProcessorVersion] - to evaluate. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - evaluation_documents (google.cloud.documentai_v1.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_v1.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.v1.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.v1.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_v1.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/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py deleted file mode 100644 index 3506f466..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py +++ /dev/null @@ -1,250 +0,0 @@ -# -*- 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 - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'DocumentSchema', - }, -) - - -class DocumentSchema(proto.Message): - r"""The schema defines the output of the processed document by a - processor. - - Attributes: - display_name (str): - Display name to show to users. - description (str): - Description of the schema. - entity_types (MutableSequence[google.cloud.documentai_v1.types.DocumentSchema.EntityType]): - Entity types of the schema. - metadata (google.cloud.documentai_v1.types.DocumentSchema.Metadata): - Metadata of the schema. - """ - - class EntityType(proto.Message): - r"""EntityType is the wrapper of a label of the corresponding - model with detailed attributes and limitations for entity-based - processors. Multiple types can also compose a dependency tree to - represent nested types. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - enum_values (google.cloud.documentai_v1.types.DocumentSchema.EntityType.EnumValues): - If specified, lists all the possible values for this entity. - This should not be more than a handful of values. If the - number of values is >10 or could change frequently use the - ``EntityType.value_ontology`` field and specify a list of - all possible values in a value ontology file. - - This field is a member of `oneof`_ ``value_source``. - display_name (str): - User defined name for the type. - name (str): - Name of the type. It must be unique within the schema file - and cannot be a 'Common Type'. Besides that we use the - following naming conventions: - - - *use ``snake_casing``* - - name matching is case-sensitive - - 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 - compatibility. - base_types (MutableSequence[str]): - The entity type that this type is derived - from. For now, one and only one should be set. - properties (MutableSequence[google.cloud.documentai_v1.types.DocumentSchema.EntityType.Property]): - Description the nested structure, or - composition of an entity. - """ - - class EnumValues(proto.Message): - r"""Defines the a list of enum values. - - Attributes: - values (MutableSequence[str]): - The individual values that this enum values - type can include. - """ - - values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class Property(proto.Message): - r"""Defines properties that can be part of the entity type. - - Attributes: - name (str): - The name of the property. Follows the same - guidelines as the EntityType name. - value_type (str): - A reference to the value type of the property. This type is - subject to the same conventions as the ``Entity.base_types`` - field. - occurrence_type (google.cloud.documentai_v1.types.DocumentSchema.EntityType.Property.OccurrenceType): - Occurrence type limits the number of - instances an entity type appears in the - document. - """ - class OccurrenceType(proto.Enum): - r"""Types of occurrences of the entity type in the document. This - represents the number of instances of instances of an entity, not - number of mentions of an entity. For example, a bank statement may - only have one ``account_number``, but this account number may be - mentioned in several places on the document. In this case the - 'account_number' would be considered a ``REQUIRED_ONCE`` entity - type. If, on the other hand, we expect a bank statement to contain - the status of multiple different accounts for the customers, the - occurrence type will be set to ``REQUIRED_MULTIPLE``. - - Values: - OCCURRENCE_TYPE_UNSPECIFIED (0): - Unspecified occurrence type. - OPTIONAL_ONCE (1): - There will be zero or one instance of this - entity type. The same entity instance may be - mentioned multiple times. - OPTIONAL_MULTIPLE (2): - The entity type will appear zero or multiple - times. - REQUIRED_ONCE (3): - The entity type will only appear exactly - once. The same entity instance may be mentioned - multiple times. - REQUIRED_MULTIPLE (4): - The entity type will appear once or more - times. - """ - OCCURRENCE_TYPE_UNSPECIFIED = 0 - OPTIONAL_ONCE = 1 - OPTIONAL_MULTIPLE = 2 - REQUIRED_ONCE = 3 - REQUIRED_MULTIPLE = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value_type: str = proto.Field( - proto.STRING, - number=2, - ) - occurrence_type: 'DocumentSchema.EntityType.Property.OccurrenceType' = proto.Field( - proto.ENUM, - number=3, - enum='DocumentSchema.EntityType.Property.OccurrenceType', - ) - - enum_values: 'DocumentSchema.EntityType.EnumValues' = proto.Field( - proto.MESSAGE, - number=14, - oneof='value_source', - message='DocumentSchema.EntityType.EnumValues', - ) - display_name: str = proto.Field( - proto.STRING, - number=13, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - base_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - properties: MutableSequence['DocumentSchema.EntityType.Property'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='DocumentSchema.EntityType.Property', - ) - - class Metadata(proto.Message): - r"""Metadata for global schema behavior. - - Attributes: - document_splitter (bool): - If true, a ``document`` entity type can be applied to - subdocument ( splitting). Otherwise, it can only be applied - to the entire document (classification). - document_allow_multiple_labels (bool): - If true, on a given page, there can be multiple ``document`` - annotations covering it. - prefixed_naming_on_properties (bool): - If set, all the nested entities must be - prefixed with the parents. - skip_naming_validation (bool): - If set, we will skip the naming format validation in the - schema. So the string values in - ``DocumentSchema.EntityType.name`` and - ``DocumentSchema.EntityType.Property.name`` will not be - checked. - """ - - document_splitter: bool = proto.Field( - proto.BOOL, - number=1, - ) - document_allow_multiple_labels: bool = proto.Field( - proto.BOOL, - number=2, - ) - prefixed_naming_on_properties: bool = proto.Field( - proto.BOOL, - number=6, - ) - skip_naming_validation: bool = proto.Field( - proto.BOOL, - number=7, - ) - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - entity_types: MutableSequence[EntityType] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=EntityType, - ) - metadata: Metadata = proto.Field( - proto.MESSAGE, - number=4, - message=Metadata, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py deleted file mode 100644 index 9f3ebd78..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/geometry.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- 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 - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'Vertex', - 'NormalizedVertex', - 'BoundingPoly', - }, -) - - -class Vertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the vertex coordinates are in the same scale as the - original image. - - Attributes: - x (int): - X coordinate. - y (int): - Y coordinate (starts from the top of the - image). - """ - - x: int = proto.Field( - proto.INT32, - number=1, - ) - y: int = proto.Field( - proto.INT32, - number=2, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate (starts from the top of the - image). - """ - - x: float = proto.Field( - proto.FLOAT, - number=1, - ) - y: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class BoundingPoly(proto.Message): - r"""A bounding polygon for the detected image annotation. - - Attributes: - vertices (MutableSequence[google.cloud.documentai_v1.types.Vertex]): - The bounding polygon vertices. - normalized_vertices (MutableSequence[google.cloud.documentai_v1.types.NormalizedVertex]): - The bounding polygon normalized vertices. - """ - - vertices: MutableSequence['Vertex'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py deleted file mode 100644 index 9053ca49..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'CommonOperationMetadata', - }, -) - - -class CommonOperationMetadata(proto.Message): - r"""The common metadata for long running operations. - - Attributes: - state (google.cloud.documentai_v1.types.CommonOperationMetadata.State): - The state of the operation. - state_message (str): - A message providing more details about the - current state of processing. - resource (str): - A related resource to this operation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - """ - class State(proto.Enum): - r"""State of the longrunning operation. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - RUNNING (1): - Operation is still running. - CANCELLING (2): - Operation is being cancelled. - SUCCEEDED (3): - Operation succeeded. - FAILED (4): - Operation failed. - CANCELLED (5): - Operation is cancelled. - """ - STATE_UNSPECIFIED = 0 - RUNNING = 1 - CANCELLING = 2 - SUCCEEDED = 3 - FAILED = 4 - CANCELLED = 5 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - resource: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py deleted file mode 100644 index e3912e16..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py +++ /dev/null @@ -1,285 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.cloud.documentai_v1.types import document_schema as gcd_document_schema -from google.cloud.documentai_v1.types import evaluation -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'ProcessorVersion', - 'Processor', - }, -) - - -class ProcessorVersion(proto.Message): - r"""A processor version is an implementation of a processor. Each - processor can have multiple versions, pre-trained by Google - internally or up-trained by the customer. At a time, a processor - can only have one default version version. So the processor's - behavior (when processing documents) is defined by a default - version - - Attributes: - name (str): - The resource name of the processor version. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}`` - display_name (str): - The display name of the processor version. - document_schema (google.cloud.documentai_v1.types.DocumentSchema): - The schema of the processor version. - Describes the output. - state (google.cloud.documentai_v1.types.ProcessorVersion.State): - The state of the processor version. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the processor version was created. - latest_evaluation (google.cloud.documentai_v1.types.EvaluationReference): - The most recently invoked evaluation for the - processor version. - 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. - google_managed (bool): - Denotes that this ProcessorVersion is managed - by google. - deprecation_info (google.cloud.documentai_v1.types.ProcessorVersion.DeprecationInfo): - If set, information about the eventual - deprecation of this version. - """ - class State(proto.Enum): - r"""The possible states of the processor version. - - Values: - STATE_UNSPECIFIED (0): - The processor version is in an unspecified - state. - DEPLOYED (1): - The processor version is deployed and can be - used for processing. - DEPLOYING (2): - The processor version is being deployed. - UNDEPLOYED (3): - The processor version is not deployed and - cannot be used for processing. - UNDEPLOYING (4): - The processor version is being undeployed. - CREATING (5): - The processor version is being created. - DELETING (6): - The processor version is being deleted. - FAILED (7): - The processor version failed and is in an - indeterminate state. - """ - STATE_UNSPECIFIED = 0 - DEPLOYED = 1 - DEPLOYING = 2 - UNDEPLOYED = 3 - UNDEPLOYING = 4 - CREATING = 5 - DELETING = 6 - FAILED = 7 - - class DeprecationInfo(proto.Message): - r"""Information about the upcoming deprecation of this processor - version. - - Attributes: - deprecation_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which this processor version will - be deprecated. - replacement_processor_version (str): - If set, the processor version that will be - used as a replacement. - """ - - deprecation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - replacement_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - 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, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - latest_evaluation: evaluation.EvaluationReference = proto.Field( - proto.MESSAGE, - number=8, - message=evaluation.EvaluationReference, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=9, - ) - kms_key_version_name: str = proto.Field( - proto.STRING, - number=10, - ) - google_managed: bool = proto.Field( - proto.BOOL, - number=11, - ) - deprecation_info: DeprecationInfo = proto.Field( - proto.MESSAGE, - number=13, - message=DeprecationInfo, - ) - - -class Processor(proto.Message): - r"""The first-class citizen for Document AI. Each processor - defines how to extract structural information from a document. - - Attributes: - name (str): - Output only. Immutable. The resource name of the processor. - 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 - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes]. - display_name (str): - The display name of the processor. - state (google.cloud.documentai_v1.types.Processor.State): - Output only. The state of the processor. - default_processor_version (str): - The default processor version. - process_endpoint (str): - Output only. Immutable. The http endpoint - that can be called to invoke processing. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the processor was created. - kms_key_name (str): - The KMS key used for encryption/decryption in - CMEK scenarios. See - https://cloud.google.com/security-key-management. - """ - class State(proto.Enum): - r"""The possible states of the processor. - - Values: - STATE_UNSPECIFIED (0): - The processor is in an unspecified state. - ENABLED (1): - The processor is enabled, i.e., has an - enabled version which can currently serve - processing requests and all the feature - dependencies have been successfully initialized. - DISABLED (2): - The processor is disabled. - ENABLING (3): - The processor is being enabled, will become ``ENABLED`` if - successful. - DISABLING (4): - The processor is being disabled, will become ``DISABLED`` if - successful. - CREATING (5): - The processor is being created, will become either - ``ENABLED`` (for successful creation) or ``FAILED`` (for - failed ones). Once a processor is in this state, it can then - be used for document processing, but the feature - dependencies of the processor might not be fully created - yet. - FAILED (6): - The processor failed during creation or - initialization of feature dependencies. The user - should delete the processor and recreate one as - all the functionalities of the processor are - disabled. - DELETING (7): - The processor is being deleted, will be - removed if successful. - """ - STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - ENABLING = 3 - DISABLING = 4 - CREATING = 5 - FAILED = 6 - DELETING = 7 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=9, - ) - process_endpoint: str = proto.Field( - proto.STRING, - number=6, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py deleted file mode 100644 index bb0e0339..00000000 --- a/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.py +++ /dev/null @@ -1,106 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.api import launch_stage_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'ProcessorType', - }, -) - - -class ProcessorType(proto.Message): - r"""A processor type is responsible for performing a certain - document understanding task on a certain type of document. - - Attributes: - name (str): - The resource name of the processor type. Format: - ``projects/{project}/processorTypes/{processor_type}`` - type_ (str): - The processor type, e.g., ``OCR_PROCESSOR``, - ``INVOICE_PROCESSOR``, etc. - category (str): - The processor category, used by UI to group - processor types. - available_locations (MutableSequence[google.cloud.documentai_v1.types.ProcessorType.LocationInfo]): - The locations in which this processor is - available. - allow_creation (bool): - Whether the processor type allows creation. - If true, users can create a processor of this - processor type. Otherwise, users need to request - access. - launch_stage (google.api.launch_stage_pb2.LaunchStage): - Launch stage of the processor type - sample_document_uris (MutableSequence[str]): - A set of Cloud Storage URIs of sample - documents for this processor. - """ - - class LocationInfo(proto.Message): - r"""The location information about where the processor is - available. - - Attributes: - location_id (str): - The location id, currently must be one of [us, eu]. - """ - - location_id: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - category: str = proto.Field( - proto.STRING, - number=3, - ) - available_locations: MutableSequence[LocationInfo] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=LocationInfo, - ) - allow_creation: bool = proto.Field( - proto.BOOL, - number=6, - ) - launch_stage: launch_stage_pb2.LaunchStage = proto.Field( - proto.ENUM, - number=8, - enum=launch_stage_pb2.LaunchStage, - ) - sample_document_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index e59b31ef..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- 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. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/documentai_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py deleted file mode 100644 index 5801f218..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 BatchProcessDocuments -# 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_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1 - - -async def sample_batch_process_documents(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py deleted file mode 100644 index 0d0d911a..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 BatchProcessDocuments -# 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_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1 - - -def sample_batch_process_documents(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py deleted file mode 100644 index e641612b..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 CreateProcessor -# 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_v1_generated_DocumentProcessorService_CreateProcessor_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_v1 - - -async def sample_create_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_CreateProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py deleted file mode 100644 index 91e1a877..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 CreateProcessor -# 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_v1_generated_DocumentProcessorService_CreateProcessor_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_v1 - - -def sample_create_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_CreateProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py deleted file mode 100644 index e72258a3..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessor -# 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_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1 - - -async def sample_delete_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py deleted file mode 100644 index 62a97410..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessor -# 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_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1 - - -def sample_delete_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py deleted file mode 100644 index e760dbd7..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessorVersion -# 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_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1 - - -async def sample_delete_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py deleted file mode 100644 index 100535d0..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessorVersion -# 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_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1 - - -def sample_delete_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py deleted file mode 100644 index af78c036..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeployProcessorVersion -# 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_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1 - - -async def sample_deploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py deleted file mode 100644 index 29e3b067..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeployProcessorVersion -# 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_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1 - - -def sample_deploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py deleted file mode 100644 index 17653881..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DisableProcessor -# 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_v1_generated_DocumentProcessorService_DisableProcessor_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_v1 - - -async def sample_disable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DisableProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py deleted file mode 100644 index b3465618..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DisableProcessor -# 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_v1_generated_DocumentProcessorService_DisableProcessor_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_v1 - - -def sample_disable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_DisableProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py deleted file mode 100644 index 83554c7a..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 EnableProcessor -# 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_v1_generated_DocumentProcessorService_EnableProcessor_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_v1 - - -async def sample_enable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_EnableProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py deleted file mode 100644 index 1070398b..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 EnableProcessor -# 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_v1_generated_DocumentProcessorService_EnableProcessor_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_v1 - - -def sample_enable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_EnableProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py deleted file mode 100644 index 2b317265..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 FetchProcessorTypes -# 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_v1_generated_DocumentProcessorService_FetchProcessorTypes_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_v1 - - -async def sample_fetch_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.fetch_processor_types(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_FetchProcessorTypes_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py deleted file mode 100644 index 8eb1f1e0..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 FetchProcessorTypes -# 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_v1_generated_DocumentProcessorService_FetchProcessorTypes_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_v1 - - -def sample_fetch_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = client.fetch_processor_types(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_FetchProcessorTypes_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py deleted file mode 100644 index 603d84b0..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessor -# 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_v1_generated_DocumentProcessorService_GetProcessor_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_v1 - - -async def sample_get_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessor_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py deleted file mode 100644 index 008ddd91..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessor -# 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_v1_generated_DocumentProcessorService_GetProcessor_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_v1 - - -def sample_get_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessor_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py deleted file mode 100644 index 20552d91..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorType -# 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_v1_generated_DocumentProcessorService_GetProcessorType_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_v1 - - -async def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessorType_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py deleted file mode 100644 index ad27f0c6..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorType -# 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_v1_generated_DocumentProcessorService_GetProcessorType_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_v1 - - -def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessorType_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py deleted file mode 100644 index c9c48239..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorVersion -# 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_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1 - - -async def sample_get_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_version(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py deleted file mode 100644 index 9e552ac2..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorVersion -# 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_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1 - - -def sample_get_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_version(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py deleted file mode 100644 index ebeab7d6..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorTypes -# 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_v1_generated_DocumentProcessorService_ListProcessorTypes_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_v1 - - -async def sample_list_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py deleted file mode 100644 index ad015a1c..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorTypes -# 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_v1_generated_DocumentProcessorService_ListProcessorTypes_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_v1 - - -def sample_list_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py deleted file mode 100644 index 1772e854..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorVersions -# 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_v1_generated_DocumentProcessorService_ListProcessorVersions_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_v1 - - -async def sample_list_processor_versions(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py deleted file mode 100644 index a7dc121c..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorVersions -# 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_v1_generated_DocumentProcessorService_ListProcessorVersions_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_v1 - - -def sample_list_processor_versions(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py deleted file mode 100644 index c90f095d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessors -# 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_v1_generated_DocumentProcessorService_ListProcessors_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_v1 - - -async def sample_list_processors(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListProcessors_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py deleted file mode 100644 index f14d4676..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessors -# 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_v1_generated_DocumentProcessorService_ListProcessors_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_v1 - - -def sample_list_processors(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListProcessors_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py deleted file mode 100644 index d5250da7..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 ProcessDocument -# 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_v1_generated_DocumentProcessorService_ProcessDocument_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_v1 - - -async def sample_process_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ProcessDocument_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py deleted file mode 100644 index 05ebfbb8..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 ProcessDocument -# 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_v1_generated_DocumentProcessorService_ProcessDocument_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_v1 - - -def sample_process_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ProcessDocument_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py deleted file mode 100644 index cc3a8df1..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- 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 ReviewDocument -# 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_v1_generated_DocumentProcessorService_ReviewDocument_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_v1 - - -async def sample_review_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ReviewDocument_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py deleted file mode 100644 index 845e5f0d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- 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 ReviewDocument -# 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_v1_generated_DocumentProcessorService_ReviewDocument_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_v1 - - -def sample_review_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ReviewDocument_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py deleted file mode 100644 index 97cfcb35..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- 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 SetDefaultProcessorVersion -# 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_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_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_v1 - - -async def sample_set_default_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py deleted file mode 100644 index 838a5131..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- 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 SetDefaultProcessorVersion -# 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_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_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_v1 - - -def sample_set_default_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py deleted file mode 100644 index b25557e8..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 UndeployProcessorVersion -# 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_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1 - - -async def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py deleted file mode 100644 index 3e75efe3..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 UndeployProcessorVersion -# 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_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1 - - -def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json deleted file mode 100644 index 96d60af2..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json +++ /dev/null @@ -1,3549 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.documentai.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-documentai", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.BatchProcessRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1_generated_document_processor_service_batch_process_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1_generated_document_processor_service_batch_process_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.BatchProcessRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1_generated_document_processor_service_batch_process_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_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_v1_generated_document_processor_service_batch_process_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1.types.Processor" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1_generated_document_processor_service_create_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_CreateProcessor_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_v1_generated_document_processor_service_create_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1.types.Processor" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1_generated_document_processor_service_create_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_CreateProcessor_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_v1_generated_document_processor_service_create_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorVersionRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_delete_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1_generated_document_processor_service_delete_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorVersionRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_delete_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_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_v1_generated_document_processor_service_delete_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1_generated_document_processor_service_delete_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1_generated_document_processor_service_delete_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1_generated_document_processor_service_delete_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessor_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_v1_generated_document_processor_service_delete_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeployProcessorVersionRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_deploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1_generated_document_processor_service_deploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeployProcessorVersionRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_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_v1_generated_document_processor_service_deploy_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DisableProcessorRequest" - }, - { - "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": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1_generated_document_processor_service_disable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DisableProcessor_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_v1_generated_document_processor_service_disable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DisableProcessorRequest" - }, - { - "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": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1_generated_document_processor_service_disable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DisableProcessor_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_v1_generated_document_processor_service_disable_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.EnableProcessorRequest" - }, - { - "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": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1_generated_document_processor_service_enable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_EnableProcessor_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_v1_generated_document_processor_service_enable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.EnableProcessorRequest" - }, - { - "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": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1_generated_document_processor_service_enable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_EnableProcessor_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_v1_generated_document_processor_service_enable_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.evaluate_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EvaluateProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_evaluate_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_evaluate_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.evaluate_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EvaluateProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_evaluate_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_evaluate_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.fetch_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "FetchProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1.types.FetchProcessorTypesResponse", - "shortName": "fetch_processor_types" - }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_fetch_processor_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_fetch_processor_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.fetch_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "FetchProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1.types.FetchProcessorTypesResponse", - "shortName": "fetch_processor_types" - }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_fetch_processor_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_evaluation", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1.types.Evaluation", - "shortName": "get_evaluation" - }, - "description": "Sample for GetEvaluation", - "file": "documentai_v1_generated_document_processor_service_get_evaluation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_get_evaluation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_evaluation", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1.types.Evaluation", - "shortName": "get_evaluation" - }, - "description": "Sample for GetEvaluation", - "file": "documentai_v1_generated_document_processor_service_get_evaluation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_get_evaluation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_type", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" - }, - { - "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_v1.types.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1_generated_document_processor_service_get_processor_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_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_v1_generated_document_processor_service_get_processor_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_type", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" - }, - { - "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_v1.types.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1_generated_document_processor_service_get_processor_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_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_v1_generated_document_processor_service_get_processor_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1.types.ProcessorVersion", - "shortName": "get_processor_version" - }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_get_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1_generated_document_processor_service_get_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.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_v1.types.ProcessorVersion", - "shortName": "get_processor_version" - }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_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_v1_generated_document_processor_service_get_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorRequest" - }, - { - "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_v1.types.Processor", - "shortName": "get_processor" - }, - "description": "Sample for GetProcessor", - "file": "documentai_v1_generated_document_processor_service_get_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_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_v1_generated_document_processor_service_get_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorRequest" - }, - { - "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_v1.types.Processor", - "shortName": "get_processor" - }, - "description": "Sample for GetProcessor", - "file": "documentai_v1_generated_document_processor_service_get_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_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_v1_generated_document_processor_service_get_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListEvaluationsAsyncPager", - "shortName": "list_evaluations" - }, - "description": "Sample for ListEvaluations", - "file": "documentai_v1_generated_document_processor_service_list_evaluations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_evaluations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListEvaluationsPager", - "shortName": "list_evaluations" - }, - "description": "Sample for ListEvaluations", - "file": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorTypesRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListProcessorTypesAsyncPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_list_processor_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorTypesRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListProcessorTypesPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_list_processor_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorVersionsRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1_generated_document_processor_service_list_processor_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorVersionsRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListProcessorVersionsPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1_generated_document_processor_service_list_processor_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorsRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListProcessorsAsyncPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1_generated_document_processor_service_list_processors_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessors_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processors_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorsRequest" - }, - { - "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_v1.services.document_processor_service.pagers.ListProcessorsPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1_generated_document_processor_service_list_processors_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessors_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processors_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ProcessRequest" - }, - { - "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_v1.types.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1_generated_document_processor_service_process_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ProcessDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_process_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ProcessRequest" - }, - { - "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_v1.types.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1_generated_document_processor_service_process_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ProcessDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_process_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "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": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1_generated_document_processor_service_review_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ReviewDocument_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_review_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "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": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1_generated_document_processor_service_review_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ReviewDocument_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_review_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest" - }, - { - "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": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_set_default_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_set_default_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest" - }, - { - "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": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.train_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "TrainProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor_version", - "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_train_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_train_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.train_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "TrainProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor_version", - "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_train_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_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_v1_generated_document_processor_service_train_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.UndeployProcessorVersionRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1_generated_document_processor_service_undeploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.UndeployProcessorVersionRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_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_v1_generated_document_processor_service_undeploy_processor_version_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py deleted file mode 100644 index 090486ac..00000000 --- a/owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py +++ /dev/null @@ -1,197 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class documentaiCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_process_documents': ('name', 'input_documents', 'document_output_config', 'skip_human_review', ), - 'create_processor': ('parent', 'processor', ), - 'delete_processor': ('name', ), - 'delete_processor_version': ('name', ), - '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_type': ('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', 'skip_human_review', 'field_mask', ), - 'review_document': ('human_review_config', 'inline_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', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=documentaiCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the documentai client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index ad9dc616..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- 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. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-documentai' - - -description = "Google Cloud Documentai API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - 'google-cloud-documentai >= 1.2.1, < 3.0.0dev', -] -url = "https://github.com/googleapis/python-documentai" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt deleted file mode 100644 index 45ffc899..00000000 --- a/owl-bot-staging/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt deleted file mode 100644 index 45ffc899..00000000 --- a/owl-bot-staging/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt deleted file mode 100644 index 45ffc899..00000000 --- a/owl-bot-staging/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt deleted file mode 100644 index e5a2433f..00000000 --- a/owl-bot-staging/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 -google-cloud-documentai==1.2.1 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt deleted file mode 100644 index 45ffc899..00000000 --- a/owl-bot-staging/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-cloud-documentai diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt deleted file mode 100644 index 45ffc899..00000000 --- a/owl-bot-staging/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-cloud-documentai diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py b/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py deleted file mode 100644 index 703be1f6..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py +++ /dev/null @@ -1,13252 +0,0 @@ -# -*- 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. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.documentai_v1.services.document_processor_service import DocumentProcessorServiceAsyncClient -from google.cloud.documentai_v1.services.document_processor_service import DocumentProcessorServiceClient -from google.cloud.documentai_v1.services.document_processor_service import pagers -from google.cloud.documentai_v1.services.document_processor_service import transports -from google.cloud.documentai_v1.types import barcode -from google.cloud.documentai_v1.types import document -from google.cloud.documentai_v1.types import document_io -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import document_schema -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import geometry -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import color_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import money_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(None) is None - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -def test_document_processor_service_client_get_transport_class(): - transport = DocumentProcessorServiceClient.get_transport_class() - available_transports = [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentProcessorServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentProcessorServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) -def test_document_processor_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "true"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "false"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_document_processor_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentProcessorServiceClient, DocumentProcessorServiceAsyncClient -]) -@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) -def test_document_processor_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", None), -]) -def test_document_processor_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_document_processor_service_client_client_options_from_dict(): - with mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentProcessorServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_processor_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ProcessRequest, - dict, -]) -def test_process_document(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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ProcessResponse( - ) - response = client.process_document(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.ProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - - -def test_process_document_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.process_document), - '__call__') as call: - client.process_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ProcessRequest() - -@pytest.mark.asyncio -async def test_process_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ProcessRequest): - 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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse( - )) - response = await client.process_document(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.ProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - - -@pytest.mark.asyncio -async def test_process_document_async_from_dict(): - await test_process_document_async(request_type=dict) - - -def test_process_document_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.ProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.process_document), - '__call__') as call: - call.return_value = document_processor_service.ProcessResponse() - client.process_document(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_process_document_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.ProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.process_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) - await client.process_document(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_process_document_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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ProcessResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.process_document( - 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_process_document_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.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_process_document_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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ProcessResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.process_document( - 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_process_document_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.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.BatchProcessRequest, - dict, -]) -def test_batch_process_documents(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.batch_process_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_process_documents(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.BatchProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_process_documents_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.batch_process_documents), - '__call__') as call: - client.batch_process_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.BatchProcessRequest() - -@pytest.mark.asyncio -async def test_batch_process_documents_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.BatchProcessRequest): - 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.batch_process_documents), - '__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.batch_process_documents(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.BatchProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_process_documents_async_from_dict(): - await test_batch_process_documents_async(request_type=dict) - - -def test_batch_process_documents_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.BatchProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_process_documents(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_batch_process_documents_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.BatchProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_process_documents(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_batch_process_documents_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.batch_process_documents), - '__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.batch_process_documents( - 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_batch_process_documents_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.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_batch_process_documents_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.batch_process_documents), - '__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.batch_process_documents( - 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_batch_process_documents_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.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.FetchProcessorTypesRequest, - dict, -]) -def test_fetch_processor_types(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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.FetchProcessorTypesResponse( - ) - response = client.fetch_processor_types(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.FetchProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -def test_fetch_processor_types_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.fetch_processor_types), - '__call__') as call: - client.fetch_processor_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.FetchProcessorTypesRequest() - -@pytest.mark.asyncio -async def test_fetch_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.FetchProcessorTypesRequest): - 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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse( - )) - response = await client.fetch_processor_types(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.FetchProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -@pytest.mark.asyncio -async def test_fetch_processor_types_async_from_dict(): - await test_fetch_processor_types_async(request_type=dict) - - -def test_fetch_processor_types_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.FetchProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_processor_types), - '__call__') as call: - call.return_value = document_processor_service.FetchProcessorTypesResponse() - client.fetch_processor_types(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_fetch_processor_types_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.FetchProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_processor_types), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) - await client.fetch_processor_types(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_fetch_processor_types_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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.FetchProcessorTypesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.fetch_processor_types( - 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_fetch_processor_types_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.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_fetch_processor_types_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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.FetchProcessorTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.fetch_processor_types( - 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_fetch_processor_types_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.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorTypesRequest, - dict, -]) -def test_list_processor_types(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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processor_types(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.ListProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_types_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_processor_types), - '__call__') as call: - client.list_processor_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorTypesRequest() - -@pytest.mark.asyncio -async def test_list_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorTypesRequest): - 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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processor_types(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.ListProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processor_types_async_from_dict(): - await test_list_processor_types_async(request_type=dict) - - -def test_list_processor_types_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.ListProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_types), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorTypesResponse() - client.list_processor_types(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_processor_types_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.ListProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_types), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) - await client.list_processor_types(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_processor_types_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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorTypesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processor_types( - 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_processor_types_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_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processor_types_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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processor_types( - 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_processor_types_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_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_list_processor_types_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_processor_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processor_types(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor_type.ProcessorType) - for i in results) -def test_list_processor_types_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_processor_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processor_types(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_processor_types_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_processor_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processor_types(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, processor_type.ProcessorType) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processor_types_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_processor_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_processor_types(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 - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type(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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - response = client.get_processor_type(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.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_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_processor_type), - '__call__') as call: - client.get_processor_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - -@pytest.mark.asyncio -async def test_get_processor_type_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorTypeRequest): - 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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - )) - response = await client.get_processor_type(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.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -@pytest.mark.asyncio -async def test_get_processor_type_async_from_dict(): - await test_get_processor_type_async(request_type=dict) - - -def test_get_processor_type_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.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = processor_type.ProcessorType() - client.get_processor_type(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_processor_type_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.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - await client.get_processor_type(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_processor_type_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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor_type( - 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_processor_type_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_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_type_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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor_type( - 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_processor_type_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_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors(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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processors(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.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_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_processors), - '__call__') as call: - client.list_processors() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - -@pytest.mark.asyncio -async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorsRequest): - 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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processors(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.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processors_async_from_dict(): - await test_list_processors_async(request_type=dict) - - -def test_list_processors_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.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorsResponse() - client.list_processors(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_processors_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.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - await client.list_processors(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_processors_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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processors( - 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_processors_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_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processors_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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processors( - 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_processors_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_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_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_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processors(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) -def test_list_processors_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_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processors(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_processors_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_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processors(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, processor.Processor) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processors_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_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_processors(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 - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor(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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.get_processor(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.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_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_processor), - '__call__') as call: - client.get_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - -@pytest.mark.asyncio -async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorRequest): - 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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.get_processor(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.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_get_processor_async_from_dict(): - await test_get_processor_async(request_type=dict) - - -def test_get_processor_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.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = processor.Processor() - client.get_processor(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_processor_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.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - await client.get_processor(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_processor_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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor( - 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_processor_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_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor( - 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_processor_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_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -@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", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_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.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - ) - response = client.get_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.GetProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - - -def test_get_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.get_processor_version), - '__call__') as call: - client.get_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_get_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorVersionRequest): - 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_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - )) - response = await client.get_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.GetProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - - -@pytest.mark.asyncio -async def test_get_processor_version_async_from_dict(): - await test_get_processor_version_async(request_type=dict) - - -def test_get_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.GetProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_version), - '__call__') as call: - call.return_value = processor.ProcessorVersion() - client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_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.GetProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) - await client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_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.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor_version( - 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_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.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_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.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor_version( - 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_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.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorVersionsRequest, - dict, -]) -def test_list_processor_versions(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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processor_versions(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.ListProcessorVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_versions_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_processor_versions), - '__call__') as call: - client.list_processor_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorVersionsRequest() - -@pytest.mark.asyncio -async def test_list_processor_versions_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorVersionsRequest): - 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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processor_versions(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.ListProcessorVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processor_versions_async_from_dict(): - await test_list_processor_versions_async(request_type=dict) - - -def test_list_processor_versions_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.ListProcessorVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_versions), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorVersionsResponse() - client.list_processor_versions(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_processor_versions_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.ListProcessorVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) - await client.list_processor_versions(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_processor_versions_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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processor_versions( - 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_processor_versions_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_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processor_versions_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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processor_versions( - 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_processor_versions_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_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - - -def test_list_processor_versions_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_processor_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processor_versions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.ProcessorVersion) - for i in results) -def test_list_processor_versions_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_processor_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processor_versions(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_processor_versions_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_processor_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processor_versions(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, processor.ProcessorVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processor_versions_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_processor_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_processor_versions(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 - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_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.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_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.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_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.delete_processor_version), - '__call__') as call: - client.delete_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_delete_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorVersionRequest): - 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.delete_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.delete_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.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_version_async_from_dict(): - await test_delete_processor_version_async(request_type=dict) - - -def test_delete_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.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_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.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_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.delete_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.delete_processor_version( - 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_delete_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.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_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.delete_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.delete_processor_version( - 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_delete_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.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_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.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.deploy_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.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_deploy_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.deploy_processor_version), - '__call__') as call: - client.deploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_deploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeployProcessorVersionRequest): - 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.deploy_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.deploy_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.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_deploy_processor_version_async_from_dict(): - await test_deploy_processor_version_async(request_type=dict) - - -def test_deploy_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.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.deploy_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_deploy_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.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.deploy_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_deploy_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.deploy_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.deploy_processor_version( - 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_deploy_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.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_deploy_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.deploy_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.deploy_processor_version( - 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_deploy_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.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_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.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undeploy_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.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undeploy_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.undeploy_processor_version), - '__call__') as call: - client.undeploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.UndeployProcessorVersionRequest): - 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.undeploy_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.undeploy_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.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async_from_dict(): - await test_undeploy_processor_version_async(request_type=dict) - - -def test_undeploy_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.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undeploy_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_undeploy_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.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undeploy_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_undeploy_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.undeploy_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.undeploy_processor_version( - 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_undeploy_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.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_undeploy_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.undeploy_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.undeploy_processor_version( - 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_undeploy_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.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor(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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.create_processor(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.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_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.create_processor), - '__call__') as call: - client.create_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - -@pytest.mark.asyncio -async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.CreateProcessorRequest): - 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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.create_processor(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.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_create_processor_async_from_dict(): - await test_create_processor_async(request_type=dict) - - -def test_create_processor_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.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = gcd_processor.Processor() - client.create_processor(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_create_processor_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.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - await client.create_processor(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_create_processor_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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(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 - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - - -def test_create_processor_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.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_processor_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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(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 - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_processor_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.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor(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.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_processor(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.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_processor_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.delete_processor), - '__call__') as call: - client.delete_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - -@pytest.mark.asyncio -async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorRequest): - 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.delete_processor), - '__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.delete_processor(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.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_async_from_dict(): - await test_delete_processor_async(request_type=dict) - - -def test_delete_processor_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.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_processor(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_delete_processor_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.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_processor(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_delete_processor_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.delete_processor), - '__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.delete_processor( - 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_delete_processor_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.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_processor_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.delete_processor), - '__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.delete_processor( - 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_delete_processor_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.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor(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.enable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.enable_processor(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.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_enable_processor_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.enable_processor), - '__call__') as call: - client.enable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - -@pytest.mark.asyncio -async def test_enable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EnableProcessorRequest): - 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.enable_processor), - '__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.enable_processor(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.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_enable_processor_async_from_dict(): - await test_enable_processor_async(request_type=dict) - - -def test_enable_processor_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.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.enable_processor(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_enable_processor_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.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.enable_processor(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'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor(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.disable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.disable_processor(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.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_disable_processor_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.disable_processor), - '__call__') as call: - client.disable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - -@pytest.mark.asyncio -async def test_disable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DisableProcessorRequest): - 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.disable_processor), - '__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.disable_processor(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.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_disable_processor_async_from_dict(): - await test_disable_processor_async(request_type=dict) - - -def test_disable_processor_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.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.disable_processor(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_disable_processor_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.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.disable_processor(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'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_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.set_default_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_default_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.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_default_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.set_default_processor_version), - '__call__') as call: - client.set_default_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_set_default_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - 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.set_default_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.set_default_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.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_default_processor_version_async_from_dict(): - await test_set_default_processor_version_async(request_type=dict) - - -def test_set_default_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.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_default_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=processor_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_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.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_default_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=processor_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document(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.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.review_document(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.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_review_document_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.review_document), - '__call__') as call: - client.review_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - -@pytest.mark.asyncio -async def test_review_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ReviewDocumentRequest): - 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.review_document), - '__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.review_document(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.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_review_document_async_from_dict(): - await test_review_document_async(request_type=dict) - - -def test_review_document_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.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.review_document(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', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_review_document_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.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.review_document(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', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -def test_review_document_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.review_document), - '__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.review_document( - human_review_config='human_review_config_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].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - - -def test_review_document_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.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - -@pytest.mark.asyncio -async def test_review_document_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.review_document), - '__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.review_document( - human_review_config='human_review_config_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].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_review_document_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.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -@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, - ) - - # 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 = 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', - ) - - # 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 - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ProcessRequest, - dict, -]) -def test_process_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.process_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - - -def test_process_document_rest_required_fields(request_type=document_processor_service.ProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.process_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_process_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.process_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_process_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_process_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_process_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ProcessRequest.pb(document_processor_service.ProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ProcessResponse.to_json(document_processor_service.ProcessResponse()) - - request = document_processor_service.ProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ProcessResponse() - - client.process_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_process_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.process_document(request) - - -def test_process_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.process_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}:process" % client.transport._host, args[1]) - - -def test_process_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - - -def test_process_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.BatchProcessRequest, - dict, -]) -def test_batch_process_documents_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_process_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_process_documents_rest_required_fields(request_type=document_processor_service.BatchProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_process_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_process_documents_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_process_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_process_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_batch_process_documents") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_batch_process_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.BatchProcessRequest.pb(document_processor_service.BatchProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.BatchProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_process_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_process_documents_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.BatchProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_process_documents(request) - - -def test_batch_process_documents_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_process_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}:batchProcess" % client.transport._host, args[1]) - - -def test_batch_process_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - - -def test_batch_process_documents_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.FetchProcessorTypesRequest, - dict, -]) -def test_fetch_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.fetch_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -def test_fetch_processor_types_rest_required_fields(request_type=document_processor_service.FetchProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.fetch_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.FetchProcessorTypesRequest.pb(document_processor_service.FetchProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.FetchProcessorTypesResponse.to_json(document_processor_service.FetchProcessorTypesResponse()) - - request = document_processor_service.FetchProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.FetchProcessorTypesResponse() - - client.fetch_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.FetchProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_processor_types(request) - - -def test_fetch_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.fetch_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}:fetchProcessorTypes" % client.transport._host, args[1]) - - -def test_fetch_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_fetch_processor_types_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorTypesRequest, - dict, -]) -def test_list_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_types_rest_required_fields(request_type=document_processor_service.ListProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorTypesRequest.pb(document_processor_service.ListProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorTypesResponse.to_json(document_processor_service.ListProcessorTypesResponse()) - - request = document_processor_service.ListProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorTypesResponse() - - client.list_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_types(request) - - -def test_list_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processorTypes" % client.transport._host, args[1]) - - -def test_list_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_list_processor_types_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processor_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor_type.ProcessorType) - for i in results) - - pages = list(client.list_processor_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_type(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_rest_required_fields(request_type=document_processor_service.GetProcessorTypeRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_type_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_type_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorTypeRequest.pb(document_processor_service.GetProcessorTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor_type.ProcessorType.to_json(processor_type.ProcessorType()) - - request = document_processor_service.GetProcessorTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor_type.ProcessorType() - - client.get_processor_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_type_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorTypeRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_type(request) - - -def test_get_processor_type_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processorTypes/*}" % client.transport._host, args[1]) - - -def test_get_processor_type_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -def test_get_processor_type_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processors(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_rest_required_fields(request_type=document_processor_service.ListProcessorsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processors(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processors_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processors._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processors_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processors") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorsRequest.pb(document_processor_service.ListProcessorsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorsResponse.to_json(document_processor_service.ListProcessorsResponse()) - - request = document_processor_service.ListProcessorsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorsResponse() - - client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processors(request) - - -def test_list_processors_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processors(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_list_processors_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processors(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) - - pages = list(client.list_processors(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_rest_required_fields(request_type=document_processor_service.GetProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorRequest.pb(document_processor_service.GetProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.Processor.to_json(processor.Processor()) - - request = document_processor_service.GetProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.Processor() - - client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor(request) - - -def test_get_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_get_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -def test_get_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.TrainProcessorVersionRequest, - dict, -]) -def test_train_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.train_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_train_processor_version_rest_required_fields(request_type=document_processor_service.TrainProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.train_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_train_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.train_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_train_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_train_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_train_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.TrainProcessorVersionRequest.pb(document_processor_service.TrainProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.TrainProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.train_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_train_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.TrainProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.train_processor_version(request) - - -def test_train_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.train_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train" % client.transport._host, args[1]) - - -def test_train_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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'), - ) - - -def test_train_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - - -def test_get_processor_version_rest_required_fields(request_type=document_processor_service.GetProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorVersionRequest.pb(document_processor_service.GetProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.ProcessorVersion.to_json(processor.ProcessorVersion()) - - request = document_processor_service.GetProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.ProcessorVersion() - - client.get_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_version(request) - - -def test_get_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_get_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - - -def test_get_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorVersionsRequest, - dict, -]) -def test_list_processor_versions_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_versions_rest_required_fields(request_type=document_processor_service.ListProcessorVersionsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_versions_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_versions_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_versions") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorVersionsRequest.pb(document_processor_service.ListProcessorVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorVersionsResponse.to_json(document_processor_service.ListProcessorVersionsResponse()) - - request = document_processor_service.ListProcessorVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorVersionsResponse() - - client.list_processor_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_versions_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorVersionsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_versions(request) - - -def test_list_processor_versions_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions" % client.transport._host, args[1]) - - -def test_list_processor_versions_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - - -def test_list_processor_versions_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorVersionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - pager = client.list_processor_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.ProcessorVersion) - for i in results) - - pages = list(client.list_processor_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_version_rest_required_fields(request_type=document_processor_service.DeleteProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorVersionRequest.pb(document_processor_service.DeleteProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor_version(request) - - -def test_delete_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_delete_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -def test_delete_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.deploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_deploy_processor_version_rest_required_fields(request_type=document_processor_service.DeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.deploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_deploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_deploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_deploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_deploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeployProcessorVersionRequest.pb(document_processor_service.DeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.deploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_deploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.deploy_processor_version(request) - - -def test_deploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.deploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" % client.transport._host, args[1]) - - -def test_deploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_deploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.undeploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_undeploy_processor_version_rest_required_fields(request_type=document_processor_service.UndeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.undeploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undeploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undeploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_undeploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_undeploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.UndeployProcessorVersionRequest.pb(document_processor_service.UndeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.UndeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undeploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undeploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.UndeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.undeploy_processor_version(request) - - -def test_undeploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.undeploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" % client.transport._host, args[1]) - - -def test_undeploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_undeploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_rest_required_fields(request_type=document_processor_service.CreateProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processor", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_create_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.CreateProcessorRequest.pb(document_processor_service.CreateProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_processor.Processor.to_json(gcd_processor.Processor()) - - request = document_processor_service.CreateProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_processor.Processor() - - client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.CreateProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_processor(request) - - -def test_create_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_create_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -def test_create_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_rest_required_fields(request_type=document_processor_service.DeleteProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorRequest.pb(document_processor_service.DeleteProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor(request) - - -def test_delete_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_delete_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -def test_delete_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.enable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_enable_processor_rest_required_fields(request_type=document_processor_service.EnableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.enable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_enable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.enable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EnableProcessorRequest.pb(document_processor_service.EnableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EnableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.enable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_enable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EnableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.enable_processor(request) - - -def test_enable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.disable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_disable_processor_rest_required_fields(request_type=document_processor_service.DisableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.disable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_disable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.disable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DisableProcessorRequest.pb(document_processor_service.DisableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DisableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.disable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_disable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DisableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.disable_processor(request) - - -def test_disable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_default_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_default_processor_version_rest_required_fields(request_type=document_processor_service.SetDefaultProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor"] = "" - request_init["default_processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processor"] = 'processor_value' - jsonified_request["defaultProcessorVersion"] = 'default_processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processor" in jsonified_request - assert jsonified_request["processor"] == 'processor_value' - assert "defaultProcessorVersion" in jsonified_request - assert jsonified_request["defaultProcessorVersion"] == 'default_processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_default_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_default_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_default_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processor", "defaultProcessorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_set_default_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_set_default_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb(document_processor_service.SetDefaultProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.SetDefaultProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_default_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_default_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_default_processor_version(request) - - -def test_set_default_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.review_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_review_document_rest_required_fields(request_type=document_processor_service.ReviewDocumentRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["human_review_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["humanReviewConfig"] = 'human_review_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "humanReviewConfig" in jsonified_request - assert jsonified_request["humanReviewConfig"] == 'human_review_config_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.review_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_review_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.review_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("humanReviewConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_review_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_review_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_review_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ReviewDocumentRequest.pb(document_processor_service.ReviewDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.ReviewDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.review_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_review_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ReviewDocumentRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.review_document(request) - - -def test_review_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - - # get truthy value for each flattened field - mock_args = dict( - human_review_config='human_review_config_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.review_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" % client.transport._host, args[1]) - - -def test_review_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -def test_review_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EvaluateProcessorVersionRequest, - dict, -]) -def test_evaluate_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.evaluate_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_evaluate_processor_version_rest_required_fields(request_type=document_processor_service.EvaluateProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processorVersion"] = 'processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processorVersion" in jsonified_request - assert jsonified_request["processorVersion"] == 'processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.evaluate_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_evaluate_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.evaluate_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_evaluate_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_evaluate_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_evaluate_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EvaluateProcessorVersionRequest.pb(document_processor_service.EvaluateProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EvaluateProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.evaluate_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_evaluate_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EvaluateProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.evaluate_processor_version(request) - - -def test_evaluate_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - processor_version='processor_version_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.evaluate_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion" % client.transport._host, args[1]) - - -def test_evaluate_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_evaluate_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetEvaluationRequest, - dict, -]) -def test_get_evaluation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_evaluation(request) - - # 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_rest_required_fields(request_type=document_processor_service.GetEvaluationRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_evaluation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_evaluation_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_evaluation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_evaluation_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_evaluation") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_evaluation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetEvaluationRequest.pb(document_processor_service.GetEvaluationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = evaluation.Evaluation.to_json(evaluation.Evaluation()) - - request = document_processor_service.GetEvaluationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = evaluation.Evaluation() - - client.get_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_evaluation_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetEvaluationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_evaluation(request) - - -def test_get_evaluation_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_evaluation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}" % client.transport._host, args[1]) - - -def test_get_evaluation_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_get_evaluation_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListEvaluationsRequest, - dict, -]) -def test_list_evaluations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_evaluations(request) - - # 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_rest_required_fields(request_type=document_processor_service.ListEvaluationsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_evaluations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_evaluations_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_evaluations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_evaluations_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_evaluations") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_evaluations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListEvaluationsRequest.pb(document_processor_service.ListEvaluationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListEvaluationsResponse.to_json(document_processor_service.ListEvaluationsResponse()) - - request = document_processor_service.ListEvaluationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListEvaluationsResponse() - - client.list_evaluations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_evaluations_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListEvaluationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_evaluations(request) - - -def test_list_evaluations_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_evaluations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations" % client.transport._host, args[1]) - - -def test_list_evaluations_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_list_evaluations_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - 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(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListEvaluationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - pager = client.list_evaluations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in results) - - pages = list(client.list_evaluations(request=sample_request).pages) - 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( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentProcessorServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentProcessorServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentProcessorServiceGrpcTransport, - ) - -def test_document_processor_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_processor_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'process_document', - 'batch_process_documents', - 'fetch_processor_types', - 'list_processor_types', - 'get_processor_type', - 'list_processors', - 'get_processor', - 'train_processor_version', - 'get_processor_version', - 'list_processor_versions', - 'delete_processor_version', - 'deploy_processor_version', - 'undeploy_processor_version', - 'create_processor', - 'delete_processor', - 'enable_processor', - 'disable_processor', - 'set_default_processor_version', - 'review_document', - 'evaluate_processor_version', - 'get_evaluation', - 'list_evaluations', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_document_processor_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_document_processor_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport() - adc.assert_called_once() - - -def test_document_processor_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentProcessorServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - ], -) -def test_document_processor_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, - ], -) -def test_document_processor_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentProcessorServiceGrpcTransport, grpc_helpers), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_processor_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_document_processor_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DocumentProcessorServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_processor_service_rest_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_no_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_with_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_processor_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentProcessorServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentProcessorServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.process_document._session - session2 = client2.transport.process_document._session - assert session1 != session2 - session1 = client1.transport.batch_process_documents._session - session2 = client2.transport.batch_process_documents._session - assert session1 != session2 - session1 = client1.transport.fetch_processor_types._session - session2 = client2.transport.fetch_processor_types._session - assert session1 != session2 - session1 = client1.transport.list_processor_types._session - session2 = client2.transport.list_processor_types._session - assert session1 != session2 - session1 = client1.transport.get_processor_type._session - session2 = client2.transport.get_processor_type._session - assert session1 != session2 - session1 = client1.transport.list_processors._session - session2 = client2.transport.list_processors._session - assert session1 != session2 - session1 = client1.transport.get_processor._session - session2 = client2.transport.get_processor._session - assert session1 != session2 - session1 = client1.transport.train_processor_version._session - session2 = client2.transport.train_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_processor_version._session - session2 = client2.transport.get_processor_version._session - assert session1 != session2 - session1 = client1.transport.list_processor_versions._session - session2 = client2.transport.list_processor_versions._session - assert session1 != session2 - session1 = client1.transport.delete_processor_version._session - session2 = client2.transport.delete_processor_version._session - assert session1 != session2 - session1 = client1.transport.deploy_processor_version._session - session2 = client2.transport.deploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.undeploy_processor_version._session - session2 = client2.transport.undeploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.create_processor._session - session2 = client2.transport.create_processor._session - assert session1 != session2 - session1 = client1.transport.delete_processor._session - session2 = client2.transport.delete_processor._session - assert session1 != session2 - session1 = client1.transport.enable_processor._session - session2 = client2.transport.enable_processor._session - assert session1 != session2 - session1 = client1.transport.disable_processor._session - session2 = client2.transport.disable_processor._session - assert session1 != session2 - session1 = client1.transport.set_default_processor_version._session - session2 = client2.transport.set_default_processor_version._session - assert session1 != session2 - session1 = client1.transport.review_document._session - session2 = client2.transport.review_document._session - assert session1 != session2 - session1 = client1.transport.evaluate_processor_version._session - session2 = client2.transport.evaluate_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_evaluation._session - session2 = client2.transport.get_evaluation._session - assert session1 != session2 - session1 = client1.transport.list_evaluations._session - session2 = client2.transport.list_evaluations._session - assert session1 != session2 -def test_document_processor_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_document_processor_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_document_processor_service_grpc_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_document_processor_service_grpc_lro_async_client(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -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, processor=processor, ) - actual = DocumentProcessorServiceClient.human_review_config_path(project, location, processor) - assert expected == actual - - -def test_parse_human_review_config_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor": "octopus", - } - path = DocumentProcessorServiceClient.human_review_config_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_human_review_config_path(path) - assert expected == actual - -def test_processor_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - actual = DocumentProcessorServiceClient.processor_path(project, location, processor) - assert expected == actual - - -def test_parse_processor_path(): - expected = { - "project": "mussel", - "location": "winkle", - "processor": "nautilus", - } - path = DocumentProcessorServiceClient.processor_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_path(path) - assert expected == actual - -def test_processor_type_path(): - project = "scallop" - location = "abalone" - processor_type = "squid" - expected = "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - actual = DocumentProcessorServiceClient.processor_type_path(project, location, processor_type) - assert expected == actual - - -def test_parse_processor_type_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor_type": "octopus", - } - path = DocumentProcessorServiceClient.processor_type_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_type_path(path) - assert expected == actual - -def test_processor_version_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - processor_version = "mussel" - expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - actual = DocumentProcessorServiceClient.processor_version_path(project, location, processor, processor_version) - assert expected == actual - - -def test_parse_processor_version_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "processor": "scallop", - "processor_version": "abalone", - } - path = DocumentProcessorServiceClient.processor_version_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentProcessorServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DocumentProcessorServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentProcessorServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DocumentProcessorServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentProcessorServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DocumentProcessorServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DocumentProcessorServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DocumentProcessorServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentProcessorServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DocumentProcessorServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentProcessorServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v1beta2/.coveragerc b/owl-bot-staging/v1beta2/.coveragerc deleted file mode 100644 index 46ab6093..00000000 --- a/owl-bot-staging/v1beta2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/documentai/__init__.py - google/cloud/documentai/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v1beta2/.flake8 b/owl-bot-staging/v1beta2/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v1beta2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1beta2/MANIFEST.in b/owl-bot-staging/v1beta2/MANIFEST.in deleted file mode 100644 index cd0fd7a8..00000000 --- a/owl-bot-staging/v1beta2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/documentai *.py -recursive-include google/cloud/documentai_v1beta2 *.py diff --git a/owl-bot-staging/v1beta2/README.rst b/owl-bot-staging/v1beta2/README.rst deleted file mode 100644 index 484a3c1c..00000000 --- a/owl-bot-staging/v1beta2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Documentai API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Documentai API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta2/docs/conf.py b/owl-bot-staging/v1beta2/docs/conf.py deleted file mode 100644 index 960a15f0..00000000 --- a/owl-bot-staging/v1beta2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- 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. -# -# -# google-cloud-documentai documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-documentai" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-documentai-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-documentai.tex", - u"google-cloud-documentai Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-documentai", - u"Google Cloud Documentai Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-documentai", - u"google-cloud-documentai Documentation", - author, - "google-cloud-documentai", - "GAPIC library for Google Cloud Documentai API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst deleted file mode 100644 index a0d0da7e..00000000 --- a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -DocumentUnderstandingService ----------------------------------------------- - -.. automodule:: google.cloud.documentai_v1beta2.services.document_understanding_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst deleted file mode 100644 index 13f4a238..00000000 --- a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Documentai v1beta2 API -================================================ -.. toctree:: - :maxdepth: 2 - - document_understanding_service diff --git a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst deleted file mode 100644 index 35540dd0..00000000 --- a/owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Documentai v1beta2 API -============================================= - -.. automodule:: google.cloud.documentai_v1beta2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta2/docs/index.rst b/owl-bot-staging/v1beta2/docs/index.rst deleted file mode 100644 index 38d5fbb5..00000000 --- a/owl-bot-staging/v1beta2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - documentai_v1beta2/services - documentai_v1beta2/types diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py deleted file mode 100644 index 0fcf1b3b..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai/__init__.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- 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 google.cloud.documentai import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.documentai_v1beta2.services.document_understanding_service.client import DocumentUnderstandingServiceClient -from google.cloud.documentai_v1beta2.services.document_understanding_service.async_client import DocumentUnderstandingServiceAsyncClient - -from google.cloud.documentai_v1beta2.types.document import Document -from google.cloud.documentai_v1beta2.types.document_understanding import AutoMlParams -from google.cloud.documentai_v1beta2.types.document_understanding import BatchProcessDocumentsRequest -from google.cloud.documentai_v1beta2.types.document_understanding import BatchProcessDocumentsResponse -from google.cloud.documentai_v1beta2.types.document_understanding import EntityExtractionParams -from google.cloud.documentai_v1beta2.types.document_understanding import FormExtractionParams -from google.cloud.documentai_v1beta2.types.document_understanding import GcsDestination -from google.cloud.documentai_v1beta2.types.document_understanding import GcsSource -from google.cloud.documentai_v1beta2.types.document_understanding import InputConfig -from google.cloud.documentai_v1beta2.types.document_understanding import KeyValuePairHint -from google.cloud.documentai_v1beta2.types.document_understanding import OcrParams -from google.cloud.documentai_v1beta2.types.document_understanding import OperationMetadata -from google.cloud.documentai_v1beta2.types.document_understanding import OutputConfig -from google.cloud.documentai_v1beta2.types.document_understanding import ProcessDocumentRequest -from google.cloud.documentai_v1beta2.types.document_understanding import ProcessDocumentResponse -from google.cloud.documentai_v1beta2.types.document_understanding import TableBoundHint -from google.cloud.documentai_v1beta2.types.document_understanding import TableExtractionParams -from google.cloud.documentai_v1beta2.types.geometry import BoundingPoly -from google.cloud.documentai_v1beta2.types.geometry import NormalizedVertex -from google.cloud.documentai_v1beta2.types.geometry import Vertex - -__all__ = ('DocumentUnderstandingServiceClient', - 'DocumentUnderstandingServiceAsyncClient', - 'Document', - 'AutoMlParams', - 'BatchProcessDocumentsRequest', - 'BatchProcessDocumentsResponse', - 'EntityExtractionParams', - 'FormExtractionParams', - 'GcsDestination', - 'GcsSource', - 'InputConfig', - 'KeyValuePairHint', - 'OcrParams', - 'OperationMetadata', - 'OutputConfig', - 'ProcessDocumentRequest', - 'ProcessDocumentResponse', - 'TableBoundHint', - 'TableExtractionParams', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py b/owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai/py.typed b/owl-bot-staging/v1beta2/google/cloud/documentai/py.typed deleted file mode 100644 index 81b45001..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py deleted file mode 100644 index fc4e4dca..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/__init__.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- 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 google.cloud.documentai_v1beta2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.document_understanding_service import DocumentUnderstandingServiceClient -from .services.document_understanding_service import DocumentUnderstandingServiceAsyncClient - -from .types.document import Document -from .types.document_understanding import AutoMlParams -from .types.document_understanding import BatchProcessDocumentsRequest -from .types.document_understanding import BatchProcessDocumentsResponse -from .types.document_understanding import EntityExtractionParams -from .types.document_understanding import FormExtractionParams -from .types.document_understanding import GcsDestination -from .types.document_understanding import GcsSource -from .types.document_understanding import InputConfig -from .types.document_understanding import KeyValuePairHint -from .types.document_understanding import OcrParams -from .types.document_understanding import OperationMetadata -from .types.document_understanding import OutputConfig -from .types.document_understanding import ProcessDocumentRequest -from .types.document_understanding import ProcessDocumentResponse -from .types.document_understanding import TableBoundHint -from .types.document_understanding import TableExtractionParams -from .types.geometry import BoundingPoly -from .types.geometry import NormalizedVertex -from .types.geometry import Vertex - -__all__ = ( - 'DocumentUnderstandingServiceAsyncClient', -'AutoMlParams', -'BatchProcessDocumentsRequest', -'BatchProcessDocumentsResponse', -'BoundingPoly', -'Document', -'DocumentUnderstandingServiceClient', -'EntityExtractionParams', -'FormExtractionParams', -'GcsDestination', -'GcsSource', -'InputConfig', -'KeyValuePairHint', -'NormalizedVertex', -'OcrParams', -'OperationMetadata', -'OutputConfig', -'ProcessDocumentRequest', -'ProcessDocumentResponse', -'TableBoundHint', -'TableExtractionParams', -'Vertex', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json deleted file mode 100644 index 633dcc19..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json +++ /dev/null @@ -1,43 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.documentai_v1beta2", - "protoPackage": "google.cloud.documentai.v1beta2", - "schema": "1.0", - "services": { - "DocumentUnderstandingService": { - "clients": { - "grpc": { - "libraryClient": "DocumentUnderstandingServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentUnderstandingServiceAsyncClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed deleted file mode 100644 index 81b45001..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- 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. -# diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py deleted file mode 100644 index 7c124f17..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- 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 .client import DocumentUnderstandingServiceClient -from .async_client import DocumentUnderstandingServiceAsyncClient - -__all__ = ( - 'DocumentUnderstandingServiceClient', - 'DocumentUnderstandingServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py deleted file mode 100644 index 8dbcefc1..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py +++ /dev/null @@ -1,426 +0,0 @@ -# -*- 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 collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.documentai_v1beta2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1beta2.types import document -from google.cloud.documentai_v1beta2.types import document_understanding -from google.rpc import status_pb2 # type: ignore -from .transports.base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DocumentUnderstandingServiceGrpcAsyncIOTransport -from .client import DocumentUnderstandingServiceClient - - -class DocumentUnderstandingServiceAsyncClient: - """Service to parse structured information from unstructured or - semi-structured documents using state-of-the-art Google AI such - as natural language, computer vision, and translation. - """ - - _client: DocumentUnderstandingServiceClient - - DEFAULT_ENDPOINT = DocumentUnderstandingServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentUnderstandingServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(DocumentUnderstandingServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentUnderstandingServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentUnderstandingServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentUnderstandingServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentUnderstandingServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentUnderstandingServiceAsyncClient: The constructed client. - """ - return DocumentUnderstandingServiceClient.from_service_account_info.__func__(DocumentUnderstandingServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentUnderstandingServiceAsyncClient: The constructed client. - """ - return DocumentUnderstandingServiceClient.from_service_account_file.__func__(DocumentUnderstandingServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentUnderstandingServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentUnderstandingServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentUnderstandingServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentUnderstandingServiceClient).get_transport_class, type(DocumentUnderstandingServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentUnderstandingServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document understanding service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.DocumentUnderstandingServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DocumentUnderstandingServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def batch_process_documents(self, - request: Optional[Union[document_understanding.BatchProcessDocumentsRequest, dict]] = None, - *, - requests: Optional[MutableSequence[document_understanding.ProcessDocumentRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. 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_v1beta2 - - async def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() - - # Initialize request argument(s) - requests = documentai_v1beta2.ProcessDocumentRequest() - requests.input_config.gcs_source.uri = "uri_value" - requests.input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.BatchProcessDocumentsRequest( - requests=requests, - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest, dict]]): - The request object. Request to batch process documents - as an asynchronous operation. The output is written to - Cloud Storage as JSON in the [Document] format. - requests (:class:`MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]`): - Required. Individual requests for - each document. - - This corresponds to the ``requests`` 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_v1beta2.types.BatchProcessDocumentsResponse` Response to an batch document processing request. This is returned in - the LRO Operation after the operation is complete. - - """ - # 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([requests]) - 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_understanding.BatchProcessDocumentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if requests: - request.requests.extend(requests) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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_understanding.BatchProcessDocumentsResponse, - metadata_type=document_understanding.OperationMetadata, - ) - - # Done; return the response. - return response - - async def process_document(self, - request: Optional[Union[document_understanding.ProcessDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Processes a single document. - - .. 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_v1beta2 - - async def sample_process_document(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() - - # Initialize request argument(s) - input_config = documentai_v1beta2.InputConfig() - input_config.gcs_source.uri = "uri_value" - input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.ProcessDocumentRequest( - input_config=input_config, - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest, dict]]): - The request object. Request to process one document. - 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_v1beta2.types.Document: - Document represents the canonical - document resource in Document - Understanding AI. It is an interchange - format that provides insights into - documents and allows for collaboration - between users and Document Understanding - AI to iterate and optimize for quality. - - """ - # Create or coerce a protobuf request object. - request = document_understanding.ProcessDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.process_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentUnderstandingServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py deleted file mode 100644 index 086c8636..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py +++ /dev/null @@ -1,606 +0,0 @@ -# -*- 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 collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.documentai_v1beta2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1beta2.types import document -from google.cloud.documentai_v1beta2.types import document_understanding -from google.rpc import status_pb2 # type: ignore -from .transports.base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentUnderstandingServiceGrpcTransport -from .transports.grpc_asyncio import DocumentUnderstandingServiceGrpcAsyncIOTransport - - -class DocumentUnderstandingServiceClientMeta(type): - """Metaclass for the DocumentUnderstandingService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentUnderstandingServiceTransport]] - _transport_registry["grpc"] = DocumentUnderstandingServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentUnderstandingServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentUnderstandingServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentUnderstandingServiceClient(metaclass=DocumentUnderstandingServiceClientMeta): - """Service to parse structured information from unstructured or - semi-structured documents using state-of-the-art Google AI such - as natural language, computer vision, and translation. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "documentai.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentUnderstandingServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentUnderstandingServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DocumentUnderstandingServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentUnderstandingServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentUnderstandingServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document understanding service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DocumentUnderstandingServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentUnderstandingServiceTransport): - # transport is a DocumentUnderstandingServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def batch_process_documents(self, - request: Optional[Union[document_understanding.BatchProcessDocumentsRequest, dict]] = None, - *, - requests: Optional[MutableSequence[document_understanding.ProcessDocumentRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. 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_v1beta2 - - def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceClient() - - # Initialize request argument(s) - requests = documentai_v1beta2.ProcessDocumentRequest() - requests.input_config.gcs_source.uri = "uri_value" - requests.input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.BatchProcessDocumentsRequest( - requests=requests, - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest, dict]): - The request object. Request to batch process documents - as an asynchronous operation. The output is written to - Cloud Storage as JSON in the [Document] format. - requests (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]): - Required. Individual requests for - each document. - - This corresponds to the ``requests`` 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_v1beta2.types.BatchProcessDocumentsResponse` Response to an batch document processing request. This is returned in - the LRO Operation after the operation is complete. - - """ - # 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([requests]) - 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_understanding.BatchProcessDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_understanding.BatchProcessDocumentsRequest): - request = document_understanding.BatchProcessDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if requests is not None: - request.requests = requests - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_process_documents] - - # 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_understanding.BatchProcessDocumentsResponse, - metadata_type=document_understanding.OperationMetadata, - ) - - # Done; return the response. - return response - - def process_document(self, - request: Optional[Union[document_understanding.ProcessDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Processes a single document. - - .. 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_v1beta2 - - def sample_process_document(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceClient() - - # Initialize request argument(s) - input_config = documentai_v1beta2.InputConfig() - input_config.gcs_source.uri = "uri_value" - input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.ProcessDocumentRequest( - input_config=input_config, - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest, dict]): - The request object. Request to process one document. - 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_v1beta2.types.Document: - Document represents the canonical - document resource in Document - Understanding AI. It is an interchange - format that provides insights into - documents and allows for collaboration - between users and Document Understanding - AI to iterate and optimize for quality. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_understanding.ProcessDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_understanding.ProcessDocumentRequest): - request = document_understanding.ProcessDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.process_document] - - # 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, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentUnderstandingServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentUnderstandingServiceClient", -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py deleted file mode 100644 index 4144c192..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- 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 collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentUnderstandingServiceTransport -from .grpc import DocumentUnderstandingServiceGrpcTransport -from .grpc_asyncio import DocumentUnderstandingServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentUnderstandingServiceTransport]] -_transport_registry['grpc'] = DocumentUnderstandingServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentUnderstandingServiceGrpcAsyncIOTransport - -__all__ = ( - 'DocumentUnderstandingServiceTransport', - 'DocumentUnderstandingServiceGrpcTransport', - 'DocumentUnderstandingServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py deleted file mode 100644 index 44c62488..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- 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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.documentai_v1beta2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.documentai_v1beta2.types import document -from google.cloud.documentai_v1beta2.types import document_understanding -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentUnderstandingServiceTransport(abc.ABC): - """Abstract transport class for DocumentUnderstandingService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'documentai.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.batch_process_documents: gapic_v1.method.wrap_method( - self.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.process_document: gapic_v1.method.wrap_method( - self.process_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def batch_process_documents(self) -> Callable[ - [document_understanding.BatchProcessDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def process_document(self) -> Callable[ - [document_understanding.ProcessDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentUnderstandingServiceTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py deleted file mode 100644 index 34e11453..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py +++ /dev/null @@ -1,313 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.documentai_v1beta2.types import document -from google.cloud.documentai_v1beta2.types import document_understanding -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentUnderstandingServiceGrpcTransport(DocumentUnderstandingServiceTransport): - """gRPC backend transport for DocumentUnderstandingService. - - Service to parse structured information from unstructured or - semi-structured documents using state-of-the-art Google AI such - as natural language, computer vision, and translation. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def batch_process_documents(self) -> Callable[ - [document_understanding.BatchProcessDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessDocumentsRequest], - ~.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 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/BatchProcessDocuments', - request_serializer=document_understanding.BatchProcessDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def process_document(self) -> Callable[ - [document_understanding.ProcessDocumentRequest], - document.Document]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessDocumentRequest], - ~.Document]: - 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 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/ProcessDocument', - request_serializer=document_understanding.ProcessDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['process_document'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentUnderstandingServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py deleted file mode 100644 index f0b3c1ff..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.documentai_v1beta2.types import document -from google.cloud.documentai_v1beta2.types import document_understanding -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentUnderstandingServiceGrpcTransport - - -class DocumentUnderstandingServiceGrpcAsyncIOTransport(DocumentUnderstandingServiceTransport): - """gRPC AsyncIO backend transport for DocumentUnderstandingService. - - Service to parse structured information from unstructured or - semi-structured documents using state-of-the-art Google AI such - as natural language, computer vision, and translation. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def batch_process_documents(self) -> Callable[ - [document_understanding.BatchProcessDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessDocumentsRequest], - 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 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/BatchProcessDocuments', - request_serializer=document_understanding.BatchProcessDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def process_document(self) -> Callable[ - [document_understanding.ProcessDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessDocumentRequest], - Awaitable[~.Document]]: - 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 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/ProcessDocument', - request_serializer=document_understanding.ProcessDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['process_document'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'DocumentUnderstandingServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py deleted file mode 100644 index b038e3b0..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- 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 .document import ( - Document, -) -from .document_understanding import ( - AutoMlParams, - BatchProcessDocumentsRequest, - BatchProcessDocumentsResponse, - EntityExtractionParams, - FormExtractionParams, - GcsDestination, - GcsSource, - InputConfig, - KeyValuePairHint, - OcrParams, - OperationMetadata, - OutputConfig, - ProcessDocumentRequest, - ProcessDocumentResponse, - TableBoundHint, - TableExtractionParams, -) -from .geometry import ( - BoundingPoly, - NormalizedVertex, - Vertex, -) - -__all__ = ( - 'Document', - 'AutoMlParams', - 'BatchProcessDocumentsRequest', - 'BatchProcessDocumentsResponse', - 'EntityExtractionParams', - 'FormExtractionParams', - 'GcsDestination', - 'GcsSource', - 'InputConfig', - 'KeyValuePairHint', - 'OcrParams', - 'OperationMetadata', - 'OutputConfig', - 'ProcessDocumentRequest', - 'ProcessDocumentResponse', - 'TableBoundHint', - 'TableExtractionParams', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py deleted file mode 100644 index 01ca727d..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py +++ /dev/null @@ -1,1080 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.cloud.documentai_v1beta2.types import geometry -from google.rpc import status_pb2 # type: ignore -from google.type import color_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta2', - manifest={ - 'Document', - }, -) - - -class Document(proto.Message): - r"""Document represents the canonical document resource in - Document Understanding AI. - It is an interchange format that provides insights into - documents and allows for collaboration between users and - Document Understanding AI to iterate and optimize for quality. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - uri (str): - Currently supports Google Cloud Storage URI of the form - ``gs://bucket_name/object_name``. Object versioning is not - supported. See `Google Cloud Storage Request - URIs `__ - for more info. - - This field is a member of `oneof`_ ``source``. - content (bytes): - Inline document content, represented as a stream of bytes. - Note: As with all ``bytes`` fields, protobuffers use a pure - binary representation, whereas JSON representations use - base64. - - This field is a member of `oneof`_ ``source``. - mime_type (str): - An IANA published MIME type (also referred to - as media type). For more information, see - https://www.iana.org/assignments/media-types/media-types.xhtml. - text (str): - UTF-8 encoded text in reading order from the - document. - text_styles (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Style]): - Styles for the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - pages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page]): - Visual page layout for the - [Document][google.cloud.documentai.v1beta2.Document]. - entities (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Entity]): - A list of entities detected on - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - For document shards, entities in this list may cross shard - boundaries. - entity_relations (MutableSequence[google.cloud.documentai_v1beta2.types.Document.EntityRelation]): - Relationship among - [Document.entities][google.cloud.documentai.v1beta2.Document.entities]. - shard_info (google.cloud.documentai_v1beta2.types.Document.ShardInfo): - Information about the sharding if this - document is sharded part of a larger document. - If the document is not sharded, this message is - not specified. - labels (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Label]): - [Label][google.cloud.documentai.v1beta2.Document.Label]s for - this document. - error (google.rpc.status_pb2.Status): - Any error that occurred while processing this - document. - """ - - class ShardInfo(proto.Message): - r"""For a large document, sharding may be performed to produce - several document shards. Each document shard contains this field - to detail which shard it is. - - Attributes: - shard_index (int): - The 0-based index of this shard. - shard_count (int): - Total number of shards. - text_offset (int): - The index of the first character in - [Document.text][google.cloud.documentai.v1beta2.Document.text] - in the overall document global text. - """ - - shard_index: int = proto.Field( - proto.INT64, - number=1, - ) - shard_count: int = proto.Field( - proto.INT64, - number=2, - ) - text_offset: int = proto.Field( - proto.INT64, - number=3, - ) - - class Label(proto.Message): - r"""Label attaches schema information and/or other metadata to segments - within a [Document][google.cloud.documentai.v1beta2.Document]. - Multiple [Label][google.cloud.documentai.v1beta2.Document.Label]s on - a single field can denote either different labels, different - instances of the same label created at different times, or some - combination of both. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - automl_model (str): - Label is generated AutoML model. This field stores the full - resource name of the AutoML model. - - Format: - ``projects/{project-id}/locations/{location-id}/models/{model-id}`` - - This field is a member of `oneof`_ ``source``. - name (str): - Name of the label. - When the label is generated from AutoML Text - Classification model, this field represents the - name of the category. - confidence (float): - Confidence score between 0 and 1 for label - assignment. - """ - - automl_model: str = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=3, - ) - - class Style(proto.Message): - r"""Annotation for common text style attributes. This adheres to - CSS conventions as much as possible. - - Attributes: - text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - color (google.type.color_pb2.Color): - Text color. - background_color (google.type.color_pb2.Color): - Text background color. - font_weight (str): - Font weight. Possible values are normal, bold, bolder, and - lighter. https://www.w3schools.com/cssref/pr_font_weight.asp - text_style (str): - Text style. Possible values are normal, italic, and oblique. - https://www.w3schools.com/cssref/pr_font_font-style.asp - text_decoration (str): - Text decoration. Follows CSS standard. - https://www.w3schools.com/cssref/pr_text_text-decoration.asp - font_size (google.cloud.documentai_v1beta2.types.Document.Style.FontSize): - Font size. - """ - - class FontSize(proto.Message): - r"""Font size with unit. - - Attributes: - size (float): - Font size for the text. - unit (str): - Unit for the font size. Follows CSS naming - (in, px, pt, etc.). - """ - - size: float = proto.Field( - proto.FLOAT, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=2, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=3, - message=color_pb2.Color, - ) - font_weight: str = proto.Field( - proto.STRING, - number=4, - ) - text_style: str = proto.Field( - proto.STRING, - number=5, - ) - text_decoration: str = proto.Field( - proto.STRING, - number=6, - ) - font_size: 'Document.Style.FontSize' = proto.Field( - proto.MESSAGE, - number=7, - message='Document.Style.FontSize', - ) - - class Page(proto.Message): - r"""A page in a [Document][google.cloud.documentai.v1beta2.Document]. - - Attributes: - page_number (int): - 1-based index for current - [Page][google.cloud.documentai.v1beta2.Document.Page] in a - parent [Document][google.cloud.documentai.v1beta2.Document]. - Useful when a page is taken out of a - [Document][google.cloud.documentai.v1beta2.Document] for - individual processing. - dimension (google.cloud.documentai_v1beta2.types.Document.Page.Dimension): - Physical dimension of the page. - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for the page. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - blocks (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Block]): - A list of visually detected text blocks on - the page. A block has a set of lines (collected - into paragraphs) that have a common line-spacing - and orientation. - paragraphs (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Paragraph]): - A list of visually detected text paragraphs - on the page. A collection of lines that a human - would perceive as a paragraph. - lines (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Line]): - A list of visually detected text lines on the - page. A collection of tokens that a human would - perceive as a line. - tokens (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Token]): - A list of visually detected tokens on the - page. - visual_elements (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.VisualElement]): - A list of detected non-text visual elements - e.g. checkbox, signature etc. on the page. - tables (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table]): - A list of visually detected tables on the - page. - form_fields (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.FormField]): - A list of visually detected form fields on - the page. - """ - - class Dimension(proto.Message): - r"""Dimension for the page. - - Attributes: - width (float): - Page width. - height (float): - Page height. - unit (str): - Dimension unit. - """ - - width: float = proto.Field( - proto.FLOAT, - number=1, - ) - height: float = proto.Field( - proto.FLOAT, - number=2, - ) - unit: str = proto.Field( - proto.STRING, - number=3, - ) - - class Layout(proto.Message): - r"""Visual element describing a layout unit on a page. - - Attributes: - text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - confidence (float): - Confidence of the current - [Layout][google.cloud.documentai.v1beta2.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]. - bounding_poly (google.cloud.documentai_v1beta2.types.BoundingPoly): - The bounding polygon for the - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout]. - orientation (google.cloud.documentai_v1beta2.types.Document.Page.Layout.Orientation): - Detected orientation for the - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout]. - id (str): - Optional. This is the identifier used by referencing - [PageAnchor][google.cloud.documentai.v1beta2.Document.PageAnchor]s. - """ - class Orientation(proto.Enum): - r"""Detected human reading orientation. - - Values: - ORIENTATION_UNSPECIFIED (0): - Unspecified orientation. - PAGE_UP (1): - Orientation is aligned with page up. - PAGE_RIGHT (2): - Orientation is aligned with page right. - Turn the head 90 degrees clockwise from upright - to read. - PAGE_DOWN (3): - Orientation is aligned with page down. - Turn the head 180 degrees from upright to read. - PAGE_LEFT (4): - Orientation is aligned with page left. - Turn the head 90 degrees counterclockwise from - upright to read. - """ - ORIENTATION_UNSPECIFIED = 0 - PAGE_UP = 1 - PAGE_RIGHT = 2 - PAGE_DOWN = 3 - PAGE_LEFT = 4 - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=3, - message=geometry.BoundingPoly, - ) - orientation: 'Document.Page.Layout.Orientation' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Page.Layout.Orientation', - ) - id: str = proto.Field( - proto.STRING, - number=5, - ) - - class Block(proto.Message): - r"""A block has a set of lines (collected into paragraphs) that - have a common line-spacing and orientation. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Block][google.cloud.documentai.v1beta2.Document.Page.Block]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class Paragraph(proto.Message): - r"""A collection of lines that a human would perceive as a - paragraph. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Paragraph][google.cloud.documentai.v1beta2.Document.Page.Paragraph]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class Line(proto.Message): - r"""A collection of tokens that a human would perceive as a line. - Does not cross column boundaries, can be horizontal, vertical, - etc. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Line][google.cloud.documentai.v1beta2.Document.Page.Line]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class Token(proto.Message): - r"""A detected token. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. - detected_break (google.cloud.documentai_v1beta2.types.Document.Page.Token.DetectedBreak): - Detected break at the end of a - [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - class DetectedBreak(proto.Message): - r"""Detected break at the end of a - [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. - - Attributes: - type_ (google.cloud.documentai_v1beta2.types.Document.Page.Token.DetectedBreak.Type): - Detected break type. - """ - class Type(proto.Enum): - r"""Enum to denote the type of break found. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified break type. - SPACE (1): - A single whitespace. - WIDE_SPACE (2): - A wider whitespace. - HYPHEN (3): - A hyphen that indicates that a token has been - split across lines. - """ - TYPE_UNSPECIFIED = 0 - SPACE = 1 - WIDE_SPACE = 2 - HYPHEN = 3 - - type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Document.Page.Token.DetectedBreak.Type', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Token.DetectedBreak', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - - class VisualElement(proto.Message): - r"""Detected non-text visual elements e.g. checkbox, signature - etc. on the page. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [VisualElement][google.cloud.documentai.v1beta2.Document.Page.VisualElement]. - type_ (str): - Type of the - [VisualElement][google.cloud.documentai.v1beta2.Document.Page.VisualElement]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - - class Table(proto.Message): - r"""A table representation similar to HTML table structure. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Table][google.cloud.documentai.v1beta2.Document.Page.Table]. - header_rows (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): - Header rows of the table. - body_rows (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): - Body rows of the table. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - class TableRow(proto.Message): - r"""A row of table cells. - - Attributes: - cells (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableCell]): - Cells that make up this row. - """ - - cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.Page.Table.TableCell', - ) - - class TableCell(proto.Message): - r"""A cell representation inside the table. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [TableCell][google.cloud.documentai.v1beta2.Document.Page.Table.TableCell]. - row_span (int): - How many rows this cell spans. - col_span (int): - How many columns this cell spans. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - row_span: int = proto.Field( - proto.INT32, - number=2, - ) - col_span: int = proto.Field( - proto.INT32, - number=3, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.Table.TableRow', - ) - body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.Table.TableRow', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - - class FormField(proto.Message): - r"""A form field detected on the page. - - Attributes: - field_name (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta2.Document.Page.FormField] - name. e.g. ``Address``, ``Email``, ``Grand total``, - ``Phone number``, etc. - field_value (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta2.Document.Page.FormField] - value. - name_detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages for name - together with confidence. - value_detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages for value - together with confidence. - value_type (str): - If the value is non-textual, this field represents the type. - Current valid values are: - - - blank (this indicates the field_value is normal text) - - "unfilled_checkbox" - - "filled_checkbox". - corrected_key_text (str): - An internal field, created for Labeling UI to - export key text. - corrected_value_text (str): - An internal field, created for Labeling UI to - export value text. - """ - - field_name: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - field_value: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Layout', - ) - name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - value_type: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_key_text: str = proto.Field( - proto.STRING, - number=6, - ) - corrected_value_text: str = proto.Field( - proto.STRING, - number=7, - ) - - class DetectedLanguage(proto.Message): - r"""Detected language for a structural component. - - Attributes: - language_code (str): - The BCP-47 language code, such as "en-US" or "sr-Latn". For - more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - confidence (float): - Confidence of detected language. Range [0, 1]. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - page_number: int = proto.Field( - proto.INT32, - number=1, - ) - dimension: 'Document.Page.Dimension' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Dimension', - ) - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Document.Page.Block', - ) - paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Document.Page.Paragraph', - ) - lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Document.Page.Line', - ) - tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='Document.Page.Token', - ) - visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Document.Page.VisualElement', - ) - tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Page.Table', - ) - form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='Document.Page.FormField', - ) - - class Entity(proto.Message): - r"""A phrase in the text that is a known entity type, such as a - person, an organization, or location. - - Attributes: - text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): - Provenance of the entity. Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - type_ (str): - Required. Entity type from a schema e.g. ``Address``. - mention_text (str): - Text value in the document e.g. ``1600 Amphitheatre Pkwy``. - mention_id (str): - Deprecated. Use ``id`` field instead. - confidence (float): - Optional. Confidence of detected Schema entity. Range [0, - 1]. - page_anchor (google.cloud.documentai_v1beta2.types.Document.PageAnchor): - Optional. Represents the provenance of this - entity wrt. the location on the page where it - was found. - id (str): - Optional. Canonical id. This will be a unique - value in the entity list for this document. - """ - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - mention_text: str = proto.Field( - proto.STRING, - number=3, - ) - mention_id: str = proto.Field( - proto.STRING, - number=4, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - page_anchor: 'Document.PageAnchor' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.PageAnchor', - ) - id: str = proto.Field( - proto.STRING, - number=7, - ) - - class EntityRelation(proto.Message): - r"""Relationship between - [Entities][google.cloud.documentai.v1beta2.Document.Entity]. - - Attributes: - subject_id (str): - Subject entity id. - object_id (str): - Object entity id. - relation (str): - Relationship description. - """ - - subject_id: str = proto.Field( - proto.STRING, - number=1, - ) - object_id: str = proto.Field( - proto.STRING, - number=2, - ) - relation: str = proto.Field( - proto.STRING, - number=3, - ) - - class TextAnchor(proto.Message): - r"""Text reference indexing into the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - - Attributes: - text_segments (MutableSequence[google.cloud.documentai_v1beta2.types.Document.TextAnchor.TextSegment]): - The text segments from the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - content (str): - Contains the content of the text span so that users do not - have to look it up in the text_segments. - """ - - class TextSegment(proto.Message): - r"""A text segment in the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. The - indices may be out of bounds which indicate that the text extends - into another document shard for large sharded documents. See - [ShardInfo.text_offset][google.cloud.documentai.v1beta2.Document.ShardInfo.text_offset] - - Attributes: - start_index (int): - [TextSegment][google.cloud.documentai.v1beta2.Document.TextAnchor.TextSegment] - start UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - end_index (int): - [TextSegment][google.cloud.documentai.v1beta2.Document.TextAnchor.TextSegment] - half open end UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - """ - - start_index: int = proto.Field( - proto.INT64, - number=1, - ) - end_index: int = proto.Field( - proto.INT64, - number=2, - ) - - text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.TextAnchor.TextSegment', - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class PageAnchor(proto.Message): - r"""Referencing elements in - [Document.pages][google.cloud.documentai.v1beta2.Document.pages]. - - Attributes: - page_refs (MutableSequence[google.cloud.documentai_v1beta2.types.Document.PageAnchor.PageRef]): - One or more references to visual page - elements - """ - - class PageRef(proto.Message): - r"""Represents a weak reference to a page element within a - document. - - Attributes: - page (int): - Required. Index into the - [Document.pages][google.cloud.documentai.v1beta2.Document.pages] - element - layout_type (google.cloud.documentai_v1beta2.types.Document.PageAnchor.PageRef.LayoutType): - Optional. The type of the layout element that - is being referenced. If not specified the whole - page is assumed to be referenced. - layout_id (str): - Optional. The - [Page.Layout.id][google.cloud.documentai.v1beta2.Document.Page.Layout.id] - on the page that this element references. If - [LayoutRef.type][] is specified this id must also be - specified. - """ - class LayoutType(proto.Enum): - r"""The type of layout that is being referenced. - - Values: - LAYOUT_TYPE_UNSPECIFIED (0): - Layout Unspecified. - BLOCK (1): - References a - [Page.blocks][google.cloud.documentai.v1beta2.Document.Page.blocks] - element. - PARAGRAPH (2): - References a - [Page.paragraphs][google.cloud.documentai.v1beta2.Document.Page.paragraphs] - element. - LINE (3): - References a - [Page.lines][google.cloud.documentai.v1beta2.Document.Page.lines] - element. - TOKEN (4): - References a - [Page.tokens][google.cloud.documentai.v1beta2.Document.Page.tokens] - element. - VISUAL_ELEMENT (5): - References a - [Page.visual_elements][google.cloud.documentai.v1beta2.Document.Page.visual_elements] - element. - TABLE (6): - Refrrences a - [Page.tables][google.cloud.documentai.v1beta2.Document.Page.tables] - element. - FORM_FIELD (7): - References a - [Page.form_fields][google.cloud.documentai.v1beta2.Document.Page.form_fields] - element. - """ - LAYOUT_TYPE_UNSPECIFIED = 0 - BLOCK = 1 - PARAGRAPH = 2 - LINE = 3 - TOKEN = 4 - VISUAL_ELEMENT = 5 - TABLE = 6 - FORM_FIELD = 7 - - page: int = proto.Field( - proto.INT64, - number=1, - ) - layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( - proto.ENUM, - number=2, - enum='Document.PageAnchor.PageRef.LayoutType', - ) - layout_id: str = proto.Field( - proto.STRING, - number=3, - ) - - page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.PageAnchor.PageRef', - ) - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - text: str = proto.Field( - proto.STRING, - number=4, - ) - text_styles: MutableSequence[Style] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Style, - ) - pages: MutableSequence[Page] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Page, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Entity, - ) - entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=EntityRelation, - ) - shard_info: ShardInfo = proto.Field( - proto.MESSAGE, - number=9, - message=ShardInfo, - ) - labels: MutableSequence[Label] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=Label, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py deleted file mode 100644 index ca3145bd..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.cloud.documentai_v1beta2.types import geometry -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta2', - manifest={ - 'BatchProcessDocumentsRequest', - 'ProcessDocumentRequest', - 'BatchProcessDocumentsResponse', - 'ProcessDocumentResponse', - 'OcrParams', - 'TableExtractionParams', - 'TableBoundHint', - 'FormExtractionParams', - 'KeyValuePairHint', - 'EntityExtractionParams', - 'AutoMlParams', - 'InputConfig', - 'OutputConfig', - 'GcsSource', - 'GcsDestination', - 'OperationMetadata', - }, -) - - -class BatchProcessDocumentsRequest(proto.Message): - r"""Request to batch process documents as an asynchronous operation. The - output is written to Cloud Storage as JSON in the [Document] format. - - Attributes: - requests (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]): - Required. Individual requests for each - document. - parent (str): - Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no location is specified, a region will be chosen - automatically. - """ - - requests: MutableSequence['ProcessDocumentRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ProcessDocumentRequest', - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ProcessDocumentRequest(proto.Message): - r"""Request to process one document. - - Attributes: - parent (str): - Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no location is specified, a region will be chosen - automatically. This field is only populated when used in - ProcessDocument method. - input_config (google.cloud.documentai_v1beta2.types.InputConfig): - Required. Information about the input file. - output_config (google.cloud.documentai_v1beta2.types.OutputConfig): - Optional. The desired output location. This - field is only needed in - BatchProcessDocumentsRequest. - document_type (str): - Specifies a known document type for deeper - structure detection. Valid values are currently - "general" and "invoice". If not provided, - "general"\ is used as default. If any other - value is given, the request is rejected. - table_extraction_params (google.cloud.documentai_v1beta2.types.TableExtractionParams): - Controls table extraction behavior. If not - specified, the system will decide reasonable - defaults. - form_extraction_params (google.cloud.documentai_v1beta2.types.FormExtractionParams): - Controls form extraction behavior. If not - specified, the system will decide reasonable - defaults. - entity_extraction_params (google.cloud.documentai_v1beta2.types.EntityExtractionParams): - Controls entity extraction behavior. If not - specified, the system will decide reasonable - defaults. - ocr_params (google.cloud.documentai_v1beta2.types.OcrParams): - Controls OCR behavior. If not specified, the - system will decide reasonable defaults. - automl_params (google.cloud.documentai_v1beta2.types.AutoMlParams): - Controls AutoML model prediction behavior. - AutoMlParams cannot be used together with other - Params. - """ - - parent: str = proto.Field( - proto.STRING, - number=9, - ) - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='InputConfig', - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='OutputConfig', - ) - document_type: str = proto.Field( - proto.STRING, - number=3, - ) - table_extraction_params: 'TableExtractionParams' = proto.Field( - proto.MESSAGE, - number=4, - message='TableExtractionParams', - ) - form_extraction_params: 'FormExtractionParams' = proto.Field( - proto.MESSAGE, - number=5, - message='FormExtractionParams', - ) - entity_extraction_params: 'EntityExtractionParams' = proto.Field( - proto.MESSAGE, - number=6, - message='EntityExtractionParams', - ) - ocr_params: 'OcrParams' = proto.Field( - proto.MESSAGE, - number=7, - message='OcrParams', - ) - automl_params: 'AutoMlParams' = proto.Field( - proto.MESSAGE, - number=8, - message='AutoMlParams', - ) - - -class BatchProcessDocumentsResponse(proto.Message): - r"""Response to an batch document processing request. This is - returned in the LRO Operation after the operation is complete. - - Attributes: - responses (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentResponse]): - Responses for each individual document. - """ - - responses: MutableSequence['ProcessDocumentResponse'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ProcessDocumentResponse', - ) - - -class ProcessDocumentResponse(proto.Message): - r"""Response to a single document processing request. - - Attributes: - input_config (google.cloud.documentai_v1beta2.types.InputConfig): - Information about the input file. This is the - same as the corresponding input config in the - request. - output_config (google.cloud.documentai_v1beta2.types.OutputConfig): - The output location of the parsed responses. The responses - are written to this location as JSON-serialized ``Document`` - objects. - """ - - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='InputConfig', - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='OutputConfig', - ) - - -class OcrParams(proto.Message): - r"""Parameters to control Optical Character Recognition (OCR) - behavior. - - Attributes: - language_hints (MutableSequence[str]): - List of languages to use for OCR. In most cases, an empty - value yields the best results since it enables automatic - language detection. For languages based on the Latin - alphabet, setting ``language_hints`` is not needed. In rare - cases, when the language of the text in the image is known, - setting a hint will help get better results (although it - will be a significant hindrance if the hint is wrong). - Document processing returns an error if one or more of the - specified languages is not one of the supported languages. - """ - - language_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class TableExtractionParams(proto.Message): - r"""Parameters to control table extraction behavior. - - Attributes: - enabled (bool): - Whether to enable table extraction. - table_bound_hints (MutableSequence[google.cloud.documentai_v1beta2.types.TableBoundHint]): - Optional. Table bounding box hints that can - be provided to complex cases which our algorithm - cannot locate the table(s) in. - header_hints (MutableSequence[str]): - Optional. Table header hints. The extraction - will bias towards producing these terms as table - headers, which may improve accuracy. - model_version (str): - Model version of the table extraction system. - Default is "builtin/stable". Specify - "builtin/latest" for the latest model. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - table_bound_hints: MutableSequence['TableBoundHint'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TableBoundHint', - ) - header_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - model_version: str = proto.Field( - proto.STRING, - number=4, - ) - - -class TableBoundHint(proto.Message): - r"""A hint for a table bounding box on the page for table - parsing. - - Attributes: - page_number (int): - Optional. Page number for multi-paged inputs - this hint applies to. If not provided, this hint - will apply to all pages by default. This value - is 1-based. - bounding_box (google.cloud.documentai_v1beta2.types.BoundingPoly): - Bounding box hint for a table on this page. The coordinates - must be normalized to [0,1] and the bounding box must be an - axis-aligned rectangle. - """ - - page_number: int = proto.Field( - proto.INT32, - number=1, - ) - bounding_box: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=2, - message=geometry.BoundingPoly, - ) - - -class FormExtractionParams(proto.Message): - r"""Parameters to control form extraction behavior. - - Attributes: - enabled (bool): - Whether to enable form extraction. - key_value_pair_hints (MutableSequence[google.cloud.documentai_v1beta2.types.KeyValuePairHint]): - User can provide pairs of (key text, value type) to improve - the parsing result. - - For example, if a document has a field called "Date" that - holds a date value and a field called "Amount" that may hold - either a currency value (e.g., "$500.00") or a simple number - value (e.g., "20"), you could use the following hints: [ - {"key": "Date", value_types: [ "DATE"]}, {"key": "Amount", - "value_types": [ "PRICE", "NUMBER" ]} ] - - If the value type is unknown, but you want to provide hints - for the keys, you can leave the value_types field blank. - e.g. {"key": "Date", "value_types": []} - model_version (str): - Model version of the form extraction system. Default is - "builtin/stable". Specify "builtin/latest" for the latest - model. For custom form models, specify: - “custom/{model_name}". Model name format is - "bucket_name/path/to/modeldir" corresponding to - "gs://bucket_name/path/to/modeldir" where annotated examples - are stored. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - key_value_pair_hints: MutableSequence['KeyValuePairHint'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='KeyValuePairHint', - ) - model_version: str = proto.Field( - proto.STRING, - number=3, - ) - - -class KeyValuePairHint(proto.Message): - r"""User-provided hint for key value pair. - - Attributes: - key (str): - The key text for the hint. - value_types (MutableSequence[str]): - Type of the value. This is case-insensitive, and could be - one of: ADDRESS, LOCATION, ORGANIZATION, PERSON, - PHONE_NUMBER, ID, NUMBER, EMAIL, PRICE, TERMS, DATE, NAME. - Types not in this list will be ignored. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - value_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class EntityExtractionParams(proto.Message): - r"""Parameters to control entity extraction behavior. - - Attributes: - enabled (bool): - Whether to enable entity extraction. - model_version (str): - Model version of the entity extraction. - Default is "builtin/stable". Specify - "builtin/latest" for the latest model. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - model_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AutoMlParams(proto.Message): - r"""Parameters to control AutoML model prediction behavior. - - Attributes: - model (str): - Resource name of the AutoML model. - - Format: - ``projects/{project-id}/locations/{location-id}/models/{model-id}``. - """ - - model: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InputConfig(proto.Message): - r"""The desired input location and metadata. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_source (google.cloud.documentai_v1beta2.types.GcsSource): - The Google Cloud Storage location to read the - input from. This must be a single file. - - This field is a member of `oneof`_ ``source``. - contents (bytes): - Content in bytes, represented as a stream of bytes. Note: As - with all ``bytes`` fields, proto buffer messages use a pure - binary representation, whereas JSON representations use - base64. - - This field only works for synchronous ProcessDocument - method. - - This field is a member of `oneof`_ ``source``. - mime_type (str): - Required. Mimetype of the input. Current supported mimetypes - are application/pdf, image/tiff, and image/gif. In addition, - application/json type is supported for requests with - [ProcessDocumentRequest.automl_params][google.cloud.documentai.v1beta2.ProcessDocumentRequest.automl_params] - field set. The JSON file needs to be in - [Document][google.cloud.documentai.v1beta2.Document] format. - """ - - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsSource', - ) - contents: bytes = proto.Field( - proto.BYTES, - number=3, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class OutputConfig(proto.Message): - r"""The desired output location and metadata. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.cloud.documentai_v1beta2.types.GcsDestination): - The Google Cloud Storage location to write - the output to. - - This field is a member of `oneof`_ ``destination``. - pages_per_shard (int): - The max number of pages to include into each output Document - shard JSON on Google Cloud Storage. - - The valid range is [1, 100]. If not specified, the default - value is 20. - - For example, for one pdf file with 100 pages, 100 parsed - pages will be produced. If ``pages_per_shard`` = 20, then 5 - Document shard JSON files each containing 20 parsed pages - will be written under the prefix - [OutputConfig.gcs_destination.uri][] and suffix - pages-x-to-y.json where x and y are 1-indexed page numbers. - - Example GCS outputs with 157 pages and pages_per_shard = 50: - - pages-001-to-050.json pages-051-to-100.json - pages-101-to-150.json pages-151-to-157.json - """ - - gcs_destination: 'GcsDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - pages_per_shard: int = proto.Field( - proto.INT32, - number=2, - ) - - -class GcsSource(proto.Message): - r"""The Google Cloud Storage location where the input file will - be read from. - - Attributes: - uri (str): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GcsDestination(proto.Message): - r"""The Google Cloud Storage location where the output file will - be written to. - - Attributes: - uri (str): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OperationMetadata(proto.Message): - r"""Contains metadata for the BatchProcessDocuments operation. - - Attributes: - state (google.cloud.documentai_v1beta2.types.OperationMetadata.State): - The state of the current batch processing. - state_message (str): - A message providing more details about the - current state of processing. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - """ - class State(proto.Enum): - r""" - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - ACCEPTED (1): - Request is received. - WAITING (2): - Request operation is waiting for scheduling. - RUNNING (3): - Request is being processed. - SUCCEEDED (4): - The batch processing completed successfully. - CANCELLED (5): - The batch processing was cancelled. - FAILED (6): - The batch processing has failed. - """ - STATE_UNSPECIFIED = 0 - ACCEPTED = 1 - WAITING = 2 - RUNNING = 3 - SUCCEEDED = 4 - CANCELLED = 5 - FAILED = 6 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py deleted file mode 100644 index 343e7a5c..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- 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 - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta2', - manifest={ - 'Vertex', - 'NormalizedVertex', - 'BoundingPoly', - }, -) - - -class Vertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the vertex coordinates are in the same scale as the - original image. - - Attributes: - x (int): - X coordinate. - y (int): - Y coordinate. - """ - - x: int = proto.Field( - proto.INT32, - number=1, - ) - y: int = proto.Field( - proto.INT32, - number=2, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate. - """ - - x: float = proto.Field( - proto.FLOAT, - number=1, - ) - y: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class BoundingPoly(proto.Message): - r"""A bounding polygon for the detected image annotation. - - Attributes: - vertices (MutableSequence[google.cloud.documentai_v1beta2.types.Vertex]): - The bounding polygon vertices. - normalized_vertices (MutableSequence[google.cloud.documentai_v1beta2.types.NormalizedVertex]): - The bounding polygon normalized vertices. - """ - - vertices: MutableSequence['Vertex'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/mypy.ini b/owl-bot-staging/v1beta2/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/owl-bot-staging/v1beta2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1beta2/noxfile.py b/owl-bot-staging/v1beta2/noxfile.py deleted file mode 100644 index 8f7cea59..00000000 --- a/owl-bot-staging/v1beta2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- 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. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/documentai_v1beta2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py deleted file mode 100644 index 366d8b41..00000000 --- a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- 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 BatchProcessDocuments -# 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_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_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_v1beta2 - - -async def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() - - # Initialize request argument(s) - requests = documentai_v1beta2.ProcessDocumentRequest() - requests.input_config.gcs_source.uri = "uri_value" - requests.input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.BatchProcessDocumentsRequest( - requests=requests, - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_async] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py deleted file mode 100644 index 22cf5eea..00000000 --- a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- 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 BatchProcessDocuments -# 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_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_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_v1beta2 - - -def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceClient() - - # Initialize request argument(s) - requests = documentai_v1beta2.ProcessDocumentRequest() - requests.input_config.gcs_source.uri = "uri_value" - requests.input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.BatchProcessDocumentsRequest( - requests=requests, - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_sync] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py deleted file mode 100644 index 586ed22a..00000000 --- a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 ProcessDocument -# 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_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_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_v1beta2 - - -async def sample_process_document(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() - - # Initialize request argument(s) - input_config = documentai_v1beta2.InputConfig() - input_config.gcs_source.uri = "uri_value" - input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.ProcessDocumentRequest( - input_config=input_config, - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_async] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py b/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py deleted file mode 100644 index 29460dd8..00000000 --- a/owl-bot-staging/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 ProcessDocument -# 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_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_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_v1beta2 - - -def sample_process_document(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceClient() - - # Initialize request argument(s) - input_config = documentai_v1beta2.InputConfig() - input_config.gcs_source.uri = "uri_value" - input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.ProcessDocumentRequest( - input_config=input_config, - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_sync] diff --git a/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json b/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json deleted file mode 100644 index ef56bd7e..00000000 --- a/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json +++ /dev/null @@ -1,329 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.documentai.v1beta2", - "version": "v1beta2" - } - ], - "language": "PYTHON", - "name": "google-cloud-documentai", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient", - "shortName": "DocumentUnderstandingServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]" - }, - { - "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": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient", - "shortName": "DocumentUnderstandingServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]" - }, - { - "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": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient", - "shortName": "DocumentUnderstandingServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.ProcessDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta2.types.Document", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta2_generated_document_understanding_service_process_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_process_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient", - "shortName": "DocumentUnderstandingServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.ProcessDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta2.types.Document", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta2_generated_document_understanding_service_process_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_process_document_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py b/owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py deleted file mode 100644 index bb31619b..00000000 --- a/owl-bot-staging/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class documentaiCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_process_documents': ('requests', 'parent', ), - 'process_document': ('input_config', 'parent', 'output_config', 'document_type', 'table_extraction_params', 'form_extraction_params', 'entity_extraction_params', 'ocr_params', 'automl_params', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=documentaiCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the documentai client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta2/setup.py b/owl-bot-staging/v1beta2/setup.py deleted file mode 100644 index 3b12ce4b..00000000 --- a/owl-bot-staging/v1beta2/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- 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. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-documentai' - - -description = "Google Cloud Documentai API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-documentai" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.10.txt b/owl-bot-staging/v1beta2/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta2/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.11.txt b/owl-bot-staging/v1beta2/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta2/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.12.txt b/owl-bot-staging/v1beta2/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta2/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.7.txt b/owl-bot-staging/v1beta2/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfe..00000000 --- a/owl-bot-staging/v1beta2/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.8.txt b/owl-bot-staging/v1beta2/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta2/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta2/testing/constraints-3.9.txt b/owl-bot-staging/v1beta2/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta2/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta2/tests/__init__.py b/owl-bot-staging/v1beta2/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/__init__.py b/owl-bot-staging/v1beta2/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py b/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py deleted file mode 100644 index 2421aee9..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py +++ /dev/null @@ -1,1570 +0,0 @@ -# -*- 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. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.documentai_v1beta2.services.document_understanding_service import DocumentUnderstandingServiceAsyncClient -from google.cloud.documentai_v1beta2.services.document_understanding_service import DocumentUnderstandingServiceClient -from google.cloud.documentai_v1beta2.services.document_understanding_service import transports -from google.cloud.documentai_v1beta2.types import document -from google.cloud.documentai_v1beta2.types import document_understanding -from google.cloud.documentai_v1beta2.types import geometry -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.rpc import status_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(None) is None - assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentUnderstandingServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentUnderstandingServiceClient, "grpc"), - (DocumentUnderstandingServiceAsyncClient, "grpc_asyncio"), -]) -def test_document_understanding_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentUnderstandingServiceGrpcTransport, "grpc"), - (transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_document_understanding_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentUnderstandingServiceClient, "grpc"), - (DocumentUnderstandingServiceAsyncClient, "grpc_asyncio"), -]) -def test_document_understanding_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - ) - - -def test_document_understanding_service_client_get_transport_class(): - transport = DocumentUnderstandingServiceClient.get_transport_class() - available_transports = [ - transports.DocumentUnderstandingServiceGrpcTransport, - ] - assert transport in available_transports - - transport = DocumentUnderstandingServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentUnderstandingServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc"), - (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(DocumentUnderstandingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceClient)) -@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceAsyncClient)) -def test_document_understanding_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(DocumentUnderstandingServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(DocumentUnderstandingServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", "true"), - (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", "false"), - (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(DocumentUnderstandingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceClient)) -@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_document_understanding_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentUnderstandingServiceClient, DocumentUnderstandingServiceAsyncClient -]) -@mock.patch.object(DocumentUnderstandingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceClient)) -@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentUnderstandingServiceAsyncClient)) -def test_document_understanding_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc"), - (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_document_understanding_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_understanding_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_document_understanding_service_client_client_options_from_dict(): - with mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentUnderstandingServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_understanding_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document_understanding.BatchProcessDocumentsRequest, - dict, -]) -def test_batch_process_documents(request_type, transport: str = 'grpc'): - client = DocumentUnderstandingServiceClient( - 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.batch_process_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_process_documents(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_understanding.BatchProcessDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_process_documents_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 = DocumentUnderstandingServiceClient( - 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.batch_process_documents), - '__call__') as call: - client.batch_process_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_understanding.BatchProcessDocumentsRequest() - -@pytest.mark.asyncio -async def test_batch_process_documents_async(transport: str = 'grpc_asyncio', request_type=document_understanding.BatchProcessDocumentsRequest): - client = DocumentUnderstandingServiceAsyncClient( - 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.batch_process_documents), - '__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.batch_process_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_understanding.BatchProcessDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_process_documents_async_from_dict(): - await test_batch_process_documents_async(request_type=dict) - - -def test_batch_process_documents_field_headers(): - client = DocumentUnderstandingServiceClient( - 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_understanding.BatchProcessDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_process_documents(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_batch_process_documents_field_headers_async(): - client = DocumentUnderstandingServiceAsyncClient( - 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_understanding.BatchProcessDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_process_documents(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_batch_process_documents_flattened(): - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__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.batch_process_documents( - requests=[document_understanding.ProcessDocumentRequest(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].requests - mock_val = [document_understanding.ProcessDocumentRequest(parent='parent_value')] - assert arg == mock_val - - -def test_batch_process_documents_flattened_error(): - client = DocumentUnderstandingServiceClient( - 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.batch_process_documents( - document_understanding.BatchProcessDocumentsRequest(), - requests=[document_understanding.ProcessDocumentRequest(parent='parent_value')], - ) - -@pytest.mark.asyncio -async def test_batch_process_documents_flattened_async(): - client = DocumentUnderstandingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__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.batch_process_documents( - requests=[document_understanding.ProcessDocumentRequest(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].requests - mock_val = [document_understanding.ProcessDocumentRequest(parent='parent_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_process_documents_flattened_error_async(): - client = DocumentUnderstandingServiceAsyncClient( - 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.batch_process_documents( - document_understanding.BatchProcessDocumentsRequest(), - requests=[document_understanding.ProcessDocumentRequest(parent='parent_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - document_understanding.ProcessDocumentRequest, - dict, -]) -def test_process_document(request_type, transport: str = 'grpc'): - client = DocumentUnderstandingServiceClient( - 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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - mime_type='mime_type_value', - text='text_value', - uri='uri_value', - ) - response = client.process_document(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_understanding.ProcessDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.mime_type == 'mime_type_value' - assert response.text == 'text_value' - - -def test_process_document_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 = DocumentUnderstandingServiceClient( - 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.process_document), - '__call__') as call: - client.process_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_understanding.ProcessDocumentRequest() - -@pytest.mark.asyncio -async def test_process_document_async(transport: str = 'grpc_asyncio', request_type=document_understanding.ProcessDocumentRequest): - client = DocumentUnderstandingServiceAsyncClient( - 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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - mime_type='mime_type_value', - text='text_value', - )) - response = await client.process_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_understanding.ProcessDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.mime_type == 'mime_type_value' - assert response.text == 'text_value' - - -@pytest.mark.asyncio -async def test_process_document_async_from_dict(): - await test_process_document_async(request_type=dict) - - -def test_process_document_field_headers(): - client = DocumentUnderstandingServiceClient( - 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_understanding.ProcessDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.process_document), - '__call__') as call: - call.return_value = document.Document() - client.process_document(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_process_document_field_headers_async(): - client = DocumentUnderstandingServiceAsyncClient( - 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_understanding.ProcessDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.process_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.process_document(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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentUnderstandingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentUnderstandingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentUnderstandingServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentUnderstandingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentUnderstandingServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentUnderstandingServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentUnderstandingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentUnderstandingServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentUnderstandingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentUnderstandingServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentUnderstandingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentUnderstandingServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentUnderstandingServiceGrpcTransport, - transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", -]) -def test_transport_kind(transport_name): - transport = DocumentUnderstandingServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentUnderstandingServiceGrpcTransport, - ) - -def test_document_understanding_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentUnderstandingServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_understanding_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentUnderstandingServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'batch_process_documents', - 'process_document', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_document_understanding_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentUnderstandingServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_document_understanding_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1beta2.services.document_understanding_service.transports.DocumentUnderstandingServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentUnderstandingServiceTransport() - adc.assert_called_once() - - -def test_document_understanding_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentUnderstandingServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentUnderstandingServiceGrpcTransport, - transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, - ], -) -def test_document_understanding_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentUnderstandingServiceGrpcTransport, - transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, - ], -) -def test_document_understanding_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentUnderstandingServiceGrpcTransport, grpc_helpers), - (transports.DocumentUnderstandingServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_understanding_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentUnderstandingServiceGrpcTransport, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport]) -def test_document_understanding_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_document_understanding_service_host_no_port(transport_name): - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_document_understanding_service_host_with_port(transport_name): - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:8000' - ) - -def test_document_understanding_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentUnderstandingServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_document_understanding_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentUnderstandingServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentUnderstandingServiceGrpcTransport, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport]) -def test_document_understanding_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentUnderstandingServiceGrpcTransport, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport]) -def test_document_understanding_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_document_understanding_service_grpc_lro_client(): - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_document_understanding_service_grpc_lro_async_client(): - client = DocumentUnderstandingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentUnderstandingServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DocumentUnderstandingServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentUnderstandingServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentUnderstandingServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DocumentUnderstandingServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentUnderstandingServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentUnderstandingServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DocumentUnderstandingServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentUnderstandingServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DocumentUnderstandingServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DocumentUnderstandingServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentUnderstandingServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentUnderstandingServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DocumentUnderstandingServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentUnderstandingServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DocumentUnderstandingServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentUnderstandingServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentUnderstandingServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentUnderstandingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = DocumentUnderstandingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport), - (DocumentUnderstandingServiceAsyncClient, transports.DocumentUnderstandingServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v1beta3/.coveragerc b/owl-bot-staging/v1beta3/.coveragerc deleted file mode 100644 index 46ab6093..00000000 --- a/owl-bot-staging/v1beta3/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/documentai/__init__.py - google/cloud/documentai/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v1beta3/.flake8 b/owl-bot-staging/v1beta3/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v1beta3/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1beta3/MANIFEST.in b/owl-bot-staging/v1beta3/MANIFEST.in deleted file mode 100644 index af799d71..00000000 --- a/owl-bot-staging/v1beta3/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/documentai *.py -recursive-include google/cloud/documentai_v1beta3 *.py diff --git a/owl-bot-staging/v1beta3/README.rst b/owl-bot-staging/v1beta3/README.rst deleted file mode 100644 index 484a3c1c..00000000 --- a/owl-bot-staging/v1beta3/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Documentai API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Documentai API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta3/docs/conf.py b/owl-bot-staging/v1beta3/docs/conf.py deleted file mode 100644 index 960a15f0..00000000 --- a/owl-bot-staging/v1beta3/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- 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. -# -# -# google-cloud-documentai documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-documentai" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-documentai-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-documentai.tex", - u"google-cloud-documentai Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-documentai", - u"Google Cloud Documentai Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-documentai", - u"google-cloud-documentai Documentation", - author, - "google-cloud-documentai", - "GAPIC library for Google Cloud Documentai API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst deleted file mode 100644 index 4d8d5f9e..00000000 --- a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/document_processor_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentProcessorService ------------------------------------------- - -.. automodule:: google.cloud.documentai_v1beta3.services.document_processor_service - :members: - :inherited-members: - -.. automodule:: google.cloud.documentai_v1beta3.services.document_processor_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst deleted file mode 100644 index d19a944b..00000000 --- a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Documentai v1beta3 API -================================================ -.. toctree:: - :maxdepth: 2 - - document_processor_service diff --git a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst deleted file mode 100644 index 31b489da..00000000 --- a/owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Documentai v1beta3 API -============================================= - -.. automodule:: google.cloud.documentai_v1beta3.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta3/docs/index.rst b/owl-bot-staging/v1beta3/docs/index.rst deleted file mode 100644 index f4d3a84d..00000000 --- a/owl-bot-staging/v1beta3/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - documentai_v1beta3/services - documentai_v1beta3/types diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py deleted file mode 100644 index 5da30913..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py +++ /dev/null @@ -1,165 +0,0 @@ -# -*- 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 google.cloud.documentai import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.documentai_v1beta3.services.document_processor_service.client import DocumentProcessorServiceClient -from google.cloud.documentai_v1beta3.services.document_processor_service.async_client import DocumentProcessorServiceAsyncClient - -from google.cloud.documentai_v1beta3.types.barcode import Barcode -from google.cloud.documentai_v1beta3.types.document import Document -from google.cloud.documentai_v1beta3.types.document_io import BatchDocumentsInputConfig -from google.cloud.documentai_v1beta3.types.document_io import DocumentOutputConfig -from google.cloud.documentai_v1beta3.types.document_io import GcsDocument -from google.cloud.documentai_v1beta3.types.document_io import GcsDocuments -from google.cloud.documentai_v1beta3.types.document_io import GcsPrefix -from google.cloud.documentai_v1beta3.types.document_io import OcrConfig -from google.cloud.documentai_v1beta3.types.document_io import RawDocument -from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import CreateProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import FetchProcessorTypesRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import FetchProcessorTypesResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import GetEvaluationRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorTypeRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import HumanReviewStatus -from google.cloud.documentai_v1beta3.types.document_processor_service import ListEvaluationsRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListEvaluationsResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorsRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorsResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorTypesRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorTypesResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorVersionsRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorVersionsResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessOptions -from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentOperationMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_schema import DocumentSchema -from google.cloud.documentai_v1beta3.types.evaluation import Evaluation -from google.cloud.documentai_v1beta3.types.evaluation import EvaluationReference -from google.cloud.documentai_v1beta3.types.geometry import BoundingPoly -from google.cloud.documentai_v1beta3.types.geometry import NormalizedVertex -from google.cloud.documentai_v1beta3.types.geometry import Vertex -from google.cloud.documentai_v1beta3.types.operation_metadata import CommonOperationMetadata -from google.cloud.documentai_v1beta3.types.processor import Processor -from google.cloud.documentai_v1beta3.types.processor import ProcessorVersion -from google.cloud.documentai_v1beta3.types.processor_type import ProcessorType - -__all__ = ('DocumentProcessorServiceClient', - 'DocumentProcessorServiceAsyncClient', - 'Barcode', - 'Document', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'OcrConfig', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessOptions', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorType', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py b/owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai/py.typed b/owl-bot-staging/v1beta3/google/cloud/documentai/py.typed deleted file mode 100644 index 81b45001..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py deleted file mode 100644 index 63a3fb42..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- 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 google.cloud.documentai_v1beta3 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.document_processor_service import DocumentProcessorServiceClient -from .services.document_processor_service import DocumentProcessorServiceAsyncClient - -from .types.barcode import Barcode -from .types.document import Document -from .types.document_io import BatchDocumentsInputConfig -from .types.document_io import DocumentOutputConfig -from .types.document_io import GcsDocument -from .types.document_io import GcsDocuments -from .types.document_io import GcsPrefix -from .types.document_io import OcrConfig -from .types.document_io import RawDocument -from .types.document_processor_service import BatchProcessMetadata -from .types.document_processor_service import BatchProcessRequest -from .types.document_processor_service import BatchProcessResponse -from .types.document_processor_service import CreateProcessorRequest -from .types.document_processor_service import DeleteProcessorMetadata -from .types.document_processor_service import DeleteProcessorRequest -from .types.document_processor_service import DeleteProcessorVersionMetadata -from .types.document_processor_service import DeleteProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionMetadata -from .types.document_processor_service import DeployProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionResponse -from .types.document_processor_service import DisableProcessorMetadata -from .types.document_processor_service import DisableProcessorRequest -from .types.document_processor_service import DisableProcessorResponse -from .types.document_processor_service import EnableProcessorMetadata -from .types.document_processor_service import EnableProcessorRequest -from .types.document_processor_service import EnableProcessorResponse -from .types.document_processor_service import EvaluateProcessorVersionMetadata -from .types.document_processor_service import EvaluateProcessorVersionRequest -from .types.document_processor_service import EvaluateProcessorVersionResponse -from .types.document_processor_service import FetchProcessorTypesRequest -from .types.document_processor_service import FetchProcessorTypesResponse -from .types.document_processor_service import GetEvaluationRequest -from .types.document_processor_service import GetProcessorRequest -from .types.document_processor_service import GetProcessorTypeRequest -from .types.document_processor_service import GetProcessorVersionRequest -from .types.document_processor_service import HumanReviewStatus -from .types.document_processor_service import ListEvaluationsRequest -from .types.document_processor_service import ListEvaluationsResponse -from .types.document_processor_service import ListProcessorsRequest -from .types.document_processor_service import ListProcessorsResponse -from .types.document_processor_service import ListProcessorTypesRequest -from .types.document_processor_service import ListProcessorTypesResponse -from .types.document_processor_service import ListProcessorVersionsRequest -from .types.document_processor_service import ListProcessorVersionsResponse -from .types.document_processor_service import ProcessOptions -from .types.document_processor_service import ProcessRequest -from .types.document_processor_service import ProcessResponse -from .types.document_processor_service import ReviewDocumentOperationMetadata -from .types.document_processor_service import ReviewDocumentRequest -from .types.document_processor_service import ReviewDocumentResponse -from .types.document_processor_service import SetDefaultProcessorVersionMetadata -from .types.document_processor_service import SetDefaultProcessorVersionRequest -from .types.document_processor_service import SetDefaultProcessorVersionResponse -from .types.document_processor_service import TrainProcessorVersionMetadata -from .types.document_processor_service import TrainProcessorVersionRequest -from .types.document_processor_service import TrainProcessorVersionResponse -from .types.document_processor_service import UndeployProcessorVersionMetadata -from .types.document_processor_service import UndeployProcessorVersionRequest -from .types.document_processor_service import UndeployProcessorVersionResponse -from .types.document_schema import DocumentSchema -from .types.evaluation import Evaluation -from .types.evaluation import EvaluationReference -from .types.geometry import BoundingPoly -from .types.geometry import NormalizedVertex -from .types.geometry import Vertex -from .types.operation_metadata import CommonOperationMetadata -from .types.processor import Processor -from .types.processor import ProcessorVersion -from .types.processor_type import ProcessorType - -__all__ = ( - 'DocumentProcessorServiceAsyncClient', -'Barcode', -'BatchDocumentsInputConfig', -'BatchProcessMetadata', -'BatchProcessRequest', -'BatchProcessResponse', -'BoundingPoly', -'CommonOperationMetadata', -'CreateProcessorRequest', -'DeleteProcessorMetadata', -'DeleteProcessorRequest', -'DeleteProcessorVersionMetadata', -'DeleteProcessorVersionRequest', -'DeployProcessorVersionMetadata', -'DeployProcessorVersionRequest', -'DeployProcessorVersionResponse', -'DisableProcessorMetadata', -'DisableProcessorRequest', -'DisableProcessorResponse', -'Document', -'DocumentOutputConfig', -'DocumentProcessorServiceClient', -'DocumentSchema', -'EnableProcessorMetadata', -'EnableProcessorRequest', -'EnableProcessorResponse', -'EvaluateProcessorVersionMetadata', -'EvaluateProcessorVersionRequest', -'EvaluateProcessorVersionResponse', -'Evaluation', -'EvaluationReference', -'FetchProcessorTypesRequest', -'FetchProcessorTypesResponse', -'GcsDocument', -'GcsDocuments', -'GcsPrefix', -'GetEvaluationRequest', -'GetProcessorRequest', -'GetProcessorTypeRequest', -'GetProcessorVersionRequest', -'HumanReviewStatus', -'ListEvaluationsRequest', -'ListEvaluationsResponse', -'ListProcessorTypesRequest', -'ListProcessorTypesResponse', -'ListProcessorVersionsRequest', -'ListProcessorVersionsResponse', -'ListProcessorsRequest', -'ListProcessorsResponse', -'NormalizedVertex', -'OcrConfig', -'ProcessOptions', -'ProcessRequest', -'ProcessResponse', -'Processor', -'ProcessorType', -'ProcessorVersion', -'RawDocument', -'ReviewDocumentOperationMetadata', -'ReviewDocumentRequest', -'ReviewDocumentResponse', -'SetDefaultProcessorVersionMetadata', -'SetDefaultProcessorVersionRequest', -'SetDefaultProcessorVersionResponse', -'TrainProcessorVersionMetadata', -'TrainProcessorVersionRequest', -'TrainProcessorVersionResponse', -'UndeployProcessorVersionMetadata', -'UndeployProcessorVersionRequest', -'UndeployProcessorVersionResponse', -'Vertex', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json deleted file mode 100644 index 95c46773..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json +++ /dev/null @@ -1,358 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.documentai_v1beta3", - "protoPackage": "google.cloud.documentai.v1beta3", - "schema": "1.0", - "services": { - "DocumentProcessorService": { - "clients": { - "grpc": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentProcessorServiceAsyncClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed deleted file mode 100644 index 81b45001..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- 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. -# diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py deleted file mode 100644 index 0e16e431..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- 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 .client import DocumentProcessorServiceClient -from .async_client import DocumentProcessorServiceAsyncClient - -__all__ = ( - 'DocumentProcessorServiceClient', - 'DocumentProcessorServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py deleted file mode 100644 index b70bd29c..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py +++ /dev/null @@ -1,2981 +0,0 @@ -# -*- 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 collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import 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 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .client import DocumentProcessorServiceClient - - -class DocumentProcessorServiceAsyncClient: - """Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - """ - - _client: DocumentProcessorServiceClient - - 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) - parse_human_review_config_path = staticmethod(DocumentProcessorServiceClient.parse_human_review_config_path) - processor_path = staticmethod(DocumentProcessorServiceClient.processor_path) - parse_processor_path = staticmethod(DocumentProcessorServiceClient.parse_processor_path) - processor_type_path = staticmethod(DocumentProcessorServiceClient.processor_type_path) - parse_processor_type_path = staticmethod(DocumentProcessorServiceClient.parse_processor_type_path) - processor_version_path = staticmethod(DocumentProcessorServiceClient.processor_version_path) - parse_processor_version_path = staticmethod(DocumentProcessorServiceClient.parse_processor_version_path) - common_billing_account_path = staticmethod(DocumentProcessorServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentProcessorServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentProcessorServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentProcessorServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentProcessorServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentProcessorServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentProcessorServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentProcessorServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentProcessorServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentProcessorServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_info.__func__(DocumentProcessorServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_file.__func__(DocumentProcessorServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentProcessorServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentProcessorServiceClient).get_transport_class, type(DocumentProcessorServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.DocumentProcessorServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DocumentProcessorServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. 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_process_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ProcessRequest, dict]]): - The request object. Request message for the process - document method. - name (:class:`str`): - Required. The resource name of the - [Processor][google.cloud.documentai.v1beta3.Processor] - or - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to use for processing. If a - [Processor][google.cloud.documentai.v1beta3.Processor] - is specified, the server will use its [default - version][google.cloud.documentai.v1beta3.Processor.default_processor_version]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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.ProcessResponse: - Response message for the process - document 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([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.ProcessRequest(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.process_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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 batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. 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_batch_process_documents(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(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.BatchProcessRequest, dict]]): - The request object. Request message for batch process - document method. - name (:class:`str`): - Required. The resource name of - [Processor][google.cloud.documentai.v1beta3.Processor] - or - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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.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.BatchProcessResponse` - Response message for batch process document 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([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.BatchProcessRequest(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.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - async def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - .. 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_fetch_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.fetch_processor_types(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest, dict]]): - The request object. Request message for fetch processor - types. - parent (:class:`str`): - Required. The project of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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.types.FetchProcessorTypesResponse: - Response message for fetch processor - types. - - """ - # 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.FetchProcessorTypesRequest(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.fetch_processor_types, - 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, - ) - - # Done; return the response. - return response - - async def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesAsyncPager: - r"""Lists the processor types that exist. - - .. 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_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest, dict]]): - The request object. Request message for list processor - types. - parent (:class:`str`): - Required. The location of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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.ListProcessorTypesAsyncPager: - Response message for list processor - types. - 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.ListProcessorTypesRequest(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_processor_types, - 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.ListProcessorTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. 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_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest, dict]]): - The request object. Request message for get processor. - name (:class:`str`): - Required. The processor type resource - name. - - 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.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # 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.GetProcessorTypeRequest(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_processor_type, - 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_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsAsyncPager: - r"""Lists all processors which belong to this project. - - .. 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_processors(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorsRequest, dict]]): - The request object. Request message for list all - processors belongs to a project. - parent (:class:`str`): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - 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.ListProcessorsAsyncPager: - Response message for list processors. - 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.ListProcessorsRequest(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_processors, - 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.ListProcessorsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. 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_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorRequest, dict]]): - The request object. Request message for get processor. - name (:class:`str`): - Required. The processor resource - name. - - 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.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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.GetProcessorRequest(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_processor, - 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 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. 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_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest, dict]]): - The request object. Request message for get processor - version. - name (:class:`str`): - Required. The processor resource - name. - - 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.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pre-trained by Google internally or - up-trained by the customer. At a time, a - processor can only have one default - version version. So the processor's - behavior (when processing documents) is - defined by a default version - - """ - # 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.GetProcessorVersionRequest(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_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(( - ("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_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsAsyncPager: - r"""Lists all versions of a processor. - - .. 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_processor_versions(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest, dict]]): - The request object. Request message for list all - processor versions belongs to a processor. - parent (:class:`str`): - Required. The parent (project, location and processor) - to list all versions. 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. - 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.ListProcessorVersionsAsyncPager: - Response message for list processors. - 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.ListProcessorVersionsRequest(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_processor_versions, - 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.ListProcessorVersionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. 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_delete_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_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.DeleteProcessorVersionRequest, dict]]): - The request object. Request message for the delete - processor version method. - name (:class:`str`): - Required. The processor version - resource name to be deleted. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorVersionRequest(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.delete_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(( - ("name", request.name), - )), - ) - - # 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, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deploys the 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_deploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_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.DeployProcessorVersionRequest, dict]]): - The request object. Request message for the deploy - processor version method. - name (:class:`str`): - Required. The processor version - resource name to be deployed. - - 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.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.DeployProcessorVersionResponse` - Response message for the deploy processor version - 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([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.DeployProcessorVersionRequest(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.deploy_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(( - ("name", request.name), - )), - ) - - # 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.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Undeploys the 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_undeploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_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.UndeployProcessorVersionRequest, dict]]): - The request object. Request message for the undeploy - processor version method. - name (:class:`str`): - Required. The processor version - resource name to be undeployed. - - 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.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.UndeployProcessorVersionResponse` - Response message for the undeploy processor version - 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([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.UndeployProcessorVersionRequest(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.undeploy_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(( - ("name", request.name), - )), - ) - - # 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.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - .. 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_create_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.CreateProcessorRequest, dict]]): - The request object. Request message for create a - processor. Notice this request is sent to a regionalized - backend service, and if the processor type is not - available on that region, the creation will fail. - parent (:class:`str`): - Required. The parent (project and location) under which - to create the processor. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor (:class:`google.cloud.documentai_v1beta3.types.Processor`): - Required. The processor to be created, requires - [processor_type] and [display_name] to be set. Also, the - processor is under CMEK if CMEK fields are set. - - This corresponds to the ``processor`` 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.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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]) - 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.CreateProcessorRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor is not None: - request.processor = processor - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_processor, - 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, - ) - - # Done; return the response. - return response - - async def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. 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_delete_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(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.DeleteProcessorRequest, dict]]): - The request object. Request message for the delete - processor method. - name (:class:`str`): - Required. The processor resource name - to be deleted. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorRequest(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.delete_processor, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - async def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Enables a processor - - .. 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_enable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(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.EnableProcessorRequest, dict]]): - The request object. Request message for the enable - processor method. - 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.EnableProcessorResponse` Response message for the enable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - request = document_processor_service.EnableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.enable_processor, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Disables a processor - - .. 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_disable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(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.DisableProcessorRequest, dict]]): - The request object. Request message for the disable - processor method. - 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.DisableProcessorResponse` Response message for the disable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - request = document_processor_service.DisableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.disable_processor, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - .. 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_set_default_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_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.SetDefaultProcessorVersionRequest, dict]]): - The request object. Request message for the set default - processor version method. - 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.SetDefaultProcessorVersionResponse` - Response message for set default processor version - method. - - """ - # Create or coerce a protobuf request object. - request = document_processor_service.SetDefaultProcessorVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_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", request.processor), - )), - ) - - # 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.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. 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_review_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(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.ReviewDocumentRequest, dict]]): - The request object. Request message for review document - method. - human_review_config (:class:`str`): - Required. The resource name of the - HumanReviewConfig that the document will - be reviewed with. - - This corresponds to the ``human_review_config`` 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.ReviewDocumentResponse` - Response message for review document 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([human_review_config]) - 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.ReviewDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if human_review_config is not None: - request.human_review_config = human_review_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.review_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - 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(( - ("human_review_config", request.human_review_config), - )), - ) - - # 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.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - 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 __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py deleted file mode 100644 index c0fbf101..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py +++ /dev/null @@ -1,3198 +0,0 @@ -# -*- 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 collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import 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 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentProcessorServiceGrpcTransport -from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .transports.rest import DocumentProcessorServiceRestTransport - - -class DocumentProcessorServiceClientMeta(type): - """Metaclass for the DocumentProcessorService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] - _transport_registry["grpc"] = DocumentProcessorServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentProcessorServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentProcessorServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentProcessorServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentProcessorServiceClient(metaclass=DocumentProcessorServiceClientMeta): - """Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "documentai.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client - instance. - """ - 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,location: str,processor: str,) -> str: - """Returns a fully-qualified human_review_config string.""" - return "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_human_review_config_path(path: str) -> Dict[str,str]: - """Parses a human_review_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/humanReviewConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified processor string.""" - return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_processor_path(path: str) -> Dict[str,str]: - """Parses a processor path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_type_path(project: str,location: str,processor_type: str,) -> str: - """Returns a fully-qualified processor_type string.""" - return "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - - @staticmethod - def parse_processor_type_path(path: str) -> Dict[str,str]: - """Parses a processor_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processorTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_version_path(project: str,location: str,processor: str,processor_version: str,) -> str: - """Returns a fully-qualified processor_version string.""" - return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - - @staticmethod - def parse_processor_version_path(path: str) -> Dict[str,str]: - """Parses a processor_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentProcessorServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DocumentProcessorServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentProcessorServiceTransport): - # transport is a DocumentProcessorServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. 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_process_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ProcessRequest, dict]): - The request object. Request message for the process - document method. - name (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1beta3.Processor] - or - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to use for processing. If a - [Processor][google.cloud.documentai.v1beta3.Processor] - is specified, the server will use its [default - version][google.cloud.documentai.v1beta3.Processor.default_processor_version]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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.ProcessResponse: - Response message for the process - document 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([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.ProcessRequest. - # 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.ProcessRequest): - request = document_processor_service.ProcessRequest(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.process_document] - - # 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 batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. 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_batch_process_documents(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.BatchProcessRequest, dict]): - The request object. Request message for batch process - document method. - name (str): - Required. The resource name of - [Processor][google.cloud.documentai.v1beta3.Processor] - or - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - 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.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.BatchProcessResponse` - Response message for batch process document 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([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.BatchProcessRequest. - # 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.BatchProcessRequest): - request = document_processor_service.BatchProcessRequest(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.batch_process_documents] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - .. 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_fetch_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = client.fetch_processor_types(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest, dict]): - The request object. Request message for fetch processor - types. - parent (str): - Required. The project of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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.types.FetchProcessorTypesResponse: - Response message for fetch processor - types. - - """ - # 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.FetchProcessorTypesRequest. - # 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.FetchProcessorTypesRequest): - request = document_processor_service.FetchProcessorTypesRequest(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.fetch_processor_types] - - # 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, - ) - - # Done; return the response. - return response - - def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesPager: - r"""Lists the processor types that exist. - - .. 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_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest, dict]): - The request object. Request message for list processor - types. - parent (str): - Required. The location of processor type to list. The - available processor types may depend on the - allow-listing on projects. Format: - ``projects/{project}/locations/{location}`` - - 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.ListProcessorTypesPager: - Response message for list processor - types. - 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.ListProcessorTypesRequest. - # 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.ListProcessorTypesRequest): - request = document_processor_service.ListProcessorTypesRequest(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_processor_types] - - # 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.ListProcessorTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. 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_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest, dict]): - The request object. Request message for get processor. - name (str): - Required. The processor type resource - name. - - 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.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # 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.GetProcessorTypeRequest. - # 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.GetProcessorTypeRequest): - request = document_processor_service.GetProcessorTypeRequest(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_processor_type] - - # 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_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsPager: - r"""Lists all processors which belong to this project. - - .. 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_processors(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListProcessorsRequest, dict]): - The request object. Request message for list all - processors belongs to a project. - parent (str): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - 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.ListProcessorsPager: - Response message for list processors. - 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.ListProcessorsRequest. - # 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.ListProcessorsRequest): - request = document_processor_service.ListProcessorsRequest(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_processors] - - # 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.ListProcessorsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. 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_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetProcessorRequest, dict]): - The request object. Request message for get processor. - name (str): - Required. The processor resource - name. - - 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.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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.GetProcessorRequest. - # 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.GetProcessorRequest): - request = document_processor_service.GetProcessorRequest(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_processor] - - # 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 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. 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_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest, dict]): - The request object. Request message for get processor - version. - name (str): - Required. The processor resource - name. - - 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.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pre-trained by Google internally or - up-trained by the customer. At a time, a - processor can only have one default - version version. So the processor's - behavior (when processing documents) is - defined by a default version - - """ - # 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.GetProcessorVersionRequest. - # 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.GetProcessorVersionRequest): - request = document_processor_service.GetProcessorVersionRequest(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_processor_version] - - # 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_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsPager: - r"""Lists all versions of a processor. - - .. 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_processor_versions(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest, dict]): - The request object. Request message for list all - processor versions belongs to a processor. - parent (str): - Required. The parent (project, location and processor) - to list all versions. 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. - 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.ListProcessorVersionsPager: - Response message for list processors. - 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.ListProcessorVersionsRequest. - # 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.ListProcessorVersionsRequest): - request = document_processor_service.ListProcessorVersionsRequest(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_processor_versions] - - # 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.ListProcessorVersionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. 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_delete_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_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.DeleteProcessorVersionRequest, dict]): - The request object. Request message for the delete - processor version method. - name (str): - Required. The processor version - resource name to be deleted. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorVersionRequest. - # 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.DeleteProcessorVersionRequest): - request = document_processor_service.DeleteProcessorVersionRequest(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.delete_processor_version] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deploys the 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_deploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_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.DeployProcessorVersionRequest, dict]): - The request object. Request message for the deploy - processor version method. - name (str): - Required. The processor version - resource name to be deployed. - - 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.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.DeployProcessorVersionResponse` - Response message for the deploy processor version - 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([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.DeployProcessorVersionRequest. - # 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.DeployProcessorVersionRequest): - request = document_processor_service.DeployProcessorVersionRequest(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.deploy_processor_version] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Undeploys the 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_undeploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_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.UndeployProcessorVersionRequest, dict]): - The request object. Request message for the undeploy - processor version method. - name (str): - Required. The processor version - resource name to be undeployed. - - 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.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.UndeployProcessorVersionResponse` - Response message for the undeploy processor version - 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([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.UndeployProcessorVersionRequest. - # 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.UndeployProcessorVersionRequest): - request = document_processor_service.UndeployProcessorVersionRequest(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.undeploy_processor_version] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - .. 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_create_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.CreateProcessorRequest, dict]): - The request object. Request message for create a - processor. Notice this request is sent to a regionalized - backend service, and if the processor type is not - available on that region, the creation will fail. - parent (str): - Required. The parent (project and location) under which - to create the processor. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor (google.cloud.documentai_v1beta3.types.Processor): - Required. The processor to be created, requires - [processor_type] and [display_name] to be set. Also, the - processor is under CMEK if CMEK fields are set. - - This corresponds to the ``processor`` 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.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - # 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]) - 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.CreateProcessorRequest. - # 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.CreateProcessorRequest): - request = document_processor_service.CreateProcessorRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor is not None: - request.processor = processor - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_processor] - - # 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, - ) - - # Done; return the response. - return response - - def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. 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_delete_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.DeleteProcessorRequest, dict]): - The request object. Request message for the delete - processor method. - name (str): - Required. The processor resource name - to be deleted. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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.DeleteProcessorRequest. - # 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.DeleteProcessorRequest): - request = document_processor_service.DeleteProcessorRequest(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.delete_processor] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Enables a processor - - .. 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_enable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.EnableProcessorRequest, dict]): - The request object. Request message for the enable - processor method. - 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.EnableProcessorResponse` Response message for the enable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.EnableProcessorRequest. - # 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.EnableProcessorRequest): - request = document_processor_service.EnableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.enable_processor] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Disables a processor - - .. 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_disable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.DisableProcessorRequest, dict]): - The request object. Request message for the disable - processor method. - 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.DisableProcessorResponse` Response message for the disable processor method. - Intentionally empty proto for adding fields in - future. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.DisableProcessorRequest. - # 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.DisableProcessorRequest): - request = document_processor_service.DisableProcessorRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.disable_processor] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - .. 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_set_default_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_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.SetDefaultProcessorVersionRequest, dict]): - The request object. Request message for the set default - processor version method. - 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.SetDefaultProcessorVersionResponse` - Response message for set default processor version - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.SetDefaultProcessorVersionRequest. - # 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.SetDefaultProcessorVersionRequest): - request = document_processor_service.SetDefaultProcessorVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_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", request.processor), - )), - ) - - # 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.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. 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_review_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ReviewDocumentRequest, dict]): - The request object. Request message for review document - method. - human_review_config (str): - Required. The resource name of the - HumanReviewConfig that the document will - be reviewed with. - - This corresponds to the ``human_review_config`` 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.ReviewDocumentResponse` - Response message for review document 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([human_review_config]) - 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.ReviewDocumentRequest. - # 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.ReviewDocumentRequest): - request = document_processor_service.ReviewDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if human_review_config is not None: - request.human_review_config = human_review_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.review_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("human_review_config", request.human_review_config), - )), - ) - - # 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.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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: Union[float, object] = gapic_v1.method.DEFAULT, - 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) -> "DocumentProcessorServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceClient", -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py deleted file mode 100644 index a7d62c87..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py +++ /dev/null @@ -1,505 +0,0 @@ -# -*- 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 Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor_type - - -class ListProcessorTypesPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` - 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.ListProcessorTypesResponse], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - 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.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse): - 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: - 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[processor_type.ProcessorType]: - for page in self.pages: - yield from page.processor_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorTypesAsyncPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` - 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.ListProcessorTypesResponse]], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - 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.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse): - 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.ListProcessorTypesRequest(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.ListProcessorTypesResponse]: - 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[processor_type.ProcessorType]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` - 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.ListProcessorsResponse], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - 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.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorsResponse): - 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.ListProcessorsRequest(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.ListProcessorsResponse]: - 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[processor.Processor]: - for page in self.pages: - yield from page.processors - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsAsyncPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` - 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.ListProcessorsResponse]], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - 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.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorsResponse): - 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.ListProcessorsRequest(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.ListProcessorsResponse]: - 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[processor.Processor]: - async def async_generator(): - async for page in self.pages: - for response in page.processors: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` - 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.ListProcessorVersionsResponse], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - 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.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse): - 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: - 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[processor.ProcessorVersion]: - for page in self.pages: - yield from page.processor_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsAsyncPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` - 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.ListProcessorVersionsResponse]], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - 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.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse): - 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.ListProcessorVersionsRequest(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.ListProcessorVersionsResponse]: - 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[processor.ProcessorVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_versions: - yield response - - return 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/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py deleted file mode 100644 index cb5f6e80..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- 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 collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentProcessorServiceTransport -from .grpc import DocumentProcessorServiceGrpcTransport -from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .rest import DocumentProcessorServiceRestTransport -from .rest import DocumentProcessorServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] -_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentProcessorServiceRestTransport - -__all__ = ( - 'DocumentProcessorServiceTransport', - 'DocumentProcessorServiceGrpcTransport', - 'DocumentProcessorServiceGrpcAsyncIOTransport', - 'DocumentProcessorServiceRestTransport', - 'DocumentProcessorServiceRestInterceptor', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py deleted file mode 100644 index a403440c..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py +++ /dev/null @@ -1,519 +0,0 @@ -# -*- 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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import 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 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentProcessorServiceTransport(abc.ABC): - """Abstract transport class for DocumentProcessorService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'documentai.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.process_document: gapic_v1.method.wrap_method( - self.process_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.batch_process_documents: gapic_v1.method.wrap_method( - self.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.fetch_processor_types: gapic_v1.method.wrap_method( - self.fetch_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.list_processor_types: gapic_v1.method.wrap_method( - self.list_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.get_processor_type: gapic_v1.method.wrap_method( - self.get_processor_type, - default_timeout=None, - client_info=client_info, - ), - self.list_processors: gapic_v1.method.wrap_method( - self.list_processors, - default_timeout=None, - client_info=client_info, - ), - self.get_processor: gapic_v1.method.wrap_method( - self.get_processor, - 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, - client_info=client_info, - ), - self.list_processor_versions: gapic_v1.method.wrap_method( - self.list_processor_versions, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor_version: gapic_v1.method.wrap_method( - self.delete_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.deploy_processor_version: gapic_v1.method.wrap_method( - self.deploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.undeploy_processor_version: gapic_v1.method.wrap_method( - self.undeploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.create_processor: gapic_v1.method.wrap_method( - self.create_processor, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor: gapic_v1.method.wrap_method( - self.delete_processor, - default_timeout=None, - client_info=client_info, - ), - self.enable_processor: gapic_v1.method.wrap_method( - self.enable_processor, - default_timeout=None, - client_info=client_info, - ), - self.disable_processor: gapic_v1.method.wrap_method( - self.disable_processor, - default_timeout=None, - client_info=client_info, - ), - self.set_default_processor_version: gapic_v1.method.wrap_method( - self.set_default_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.review_document: gapic_v1.method.wrap_method( - self.review_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - 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): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - Union[ - document_processor_service.ProcessResponse, - Awaitable[document_processor_service.ProcessResponse] - ]]: - raise NotImplementedError() - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - Union[ - document_processor_service.FetchProcessorTypesResponse, - Awaitable[document_processor_service.FetchProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Union[ - document_processor_service.ListProcessorTypesResponse, - Awaitable[document_processor_service.ListProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Union[ - processor_type.ProcessorType, - Awaitable[processor_type.ProcessorType] - ]]: - raise NotImplementedError() - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Union[ - document_processor_service.ListProcessorsResponse, - Awaitable[document_processor_service.ListProcessorsResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Union[ - processor.Processor, - Awaitable[processor.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) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Union[ - processor.ProcessorVersion, - Awaitable[processor.ProcessorVersion] - ]]: - raise NotImplementedError() - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Union[ - document_processor_service.ListProcessorVersionsResponse, - Awaitable[document_processor_service.ListProcessorVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Union[ - gcd_processor.Processor, - Awaitable[gcd_processor.Processor] - ]]: - raise NotImplementedError() - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - 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, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentProcessorServiceTransport', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py deleted file mode 100644 index 05918993..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py +++ /dev/null @@ -1,945 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import 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 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentProcessorServiceGrpcTransport(DocumentProcessorServiceTransport): - """gRPC backend transport for DocumentProcessorService. - - Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessRequest], - ~.ProcessResponse]: - 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 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ProcessDocument', - request_serializer=document_processor_service.ProcessRequest.serialize, - response_deserializer=document_processor_service.ProcessResponse.deserialize, - ) - return self._stubs['process_document'] - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessRequest], - ~.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 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/BatchProcessDocuments', - request_serializer=document_processor_service.BatchProcessRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - r"""Return a callable for the fetch processor types method over gRPC. - - Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - ~.FetchProcessorTypesResponse]: - 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 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - ~.ListProcessorTypesResponse]: - 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_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - ~.ProcessorType]: - 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_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - ~.ListProcessorsResponse]: - 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_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - ~.Processor]: - 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_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - 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) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - ~.ProcessorVersion]: - 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_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - ~.ListProcessorVersionsResponse]: - 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_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - ~.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 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - ~.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 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - ~.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 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - ~.Processor]: - 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 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - ~.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 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - ~.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 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - ~.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 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - ~.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 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - ~.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 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentProcessorServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py deleted file mode 100644 index 5b7c532c..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,944 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -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 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 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentProcessorServiceGrpcTransport - - -class DocumentProcessorServiceGrpcAsyncIOTransport(DocumentProcessorServiceTransport): - """gRPC AsyncIO backend transport for DocumentProcessorService. - - Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - Awaitable[document_processor_service.ProcessResponse]]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessRequest], - Awaitable[~.ProcessResponse]]: - 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 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ProcessDocument', - request_serializer=document_processor_service.ProcessRequest.serialize, - response_deserializer=document_processor_service.ProcessResponse.deserialize, - ) - return self._stubs['process_document'] - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessRequest], - 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 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/BatchProcessDocuments', - request_serializer=document_processor_service.BatchProcessRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - Awaitable[document_processor_service.FetchProcessorTypesResponse]]: - r"""Return a callable for the fetch processor types method over gRPC. - - Fetches processor types. Note that we do not use - ListProcessorTypes here because it is not paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - Awaitable[~.FetchProcessorTypesResponse]]: - 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 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Awaitable[document_processor_service.ListProcessorTypesResponse]]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - Awaitable[~.ListProcessorTypesResponse]]: - 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_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Awaitable[processor_type.ProcessorType]]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - Awaitable[~.ProcessorType]]: - 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_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Awaitable[document_processor_service.ListProcessorsResponse]]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - Awaitable[~.ListProcessorsResponse]]: - 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_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Awaitable[processor.Processor]]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - Awaitable[~.Processor]]: - 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_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - 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) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Awaitable[processor.ProcessorVersion]]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - Awaitable[~.ProcessorVersion]]: - 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_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Awaitable[document_processor_service.ListProcessorVersionsResponse]]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - Awaitable[~.ListProcessorVersionsResponse]]: - 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_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - 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 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - 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 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - 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 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Awaitable[gcd_processor.Processor]]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the type processor that the - user chose. The processor will be at "ENABLED" state by - default after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - Awaitable[~.Processor]]: - 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 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - 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 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - 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 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - 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 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - 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 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - 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 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'DocumentProcessorServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py deleted file mode 100644 index 897873a3..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py +++ /dev/null @@ -1,3280 +0,0 @@ -# -*- 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import 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 -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentProcessorServiceRestInterceptor: - """Interceptor for DocumentProcessorService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DocumentProcessorServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentProcessorServiceInterceptor(DocumentProcessorServiceRestInterceptor): - def pre_batch_process_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_process_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_deploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_deploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_disable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_disable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_enable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_enable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_evaluate_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_evaluate_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_fetch_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_fetch_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_evaluation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_evaluation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_evaluations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_evaluations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processors(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processors(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_process_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_process_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_review_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_review_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_default_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_default_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_train_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_train_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undeploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undeploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentProcessorServiceRestTransport(interceptor=MyCustomDocumentProcessorServiceInterceptor()) - client = DocumentProcessorServiceClient(transport=transport) - - - """ - def pre_batch_process_documents(self, request: document_processor_service.BatchProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.BatchProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_batch_process_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_create_processor(self, request: document_processor_service.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.CreateProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_create_processor(self, response: gcd_processor.Processor) -> gcd_processor.Processor: - """Post-rpc interceptor for create_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor(self, request: document_processor_service.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor_version(self, request: document_processor_service.DeleteProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_deploy_processor_version(self, request: document_processor_service.DeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_deploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_disable_processor(self, request: document_processor_service.DisableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DisableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for disable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_disable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for disable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_enable_processor(self, request: document_processor_service.EnableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EnableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for enable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_enable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for enable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_evaluate_processor_version(self, request: document_processor_service.EvaluateProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EvaluateProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_evaluate_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_fetch_processor_types(self, request: document_processor_service.FetchProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.FetchProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_fetch_processor_types(self, response: document_processor_service.FetchProcessorTypesResponse) -> document_processor_service.FetchProcessorTypesResponse: - """Post-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_evaluation(self, request: document_processor_service.GetEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_evaluation(self, response: evaluation.Evaluation) -> evaluation.Evaluation: - """Post-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor(self, request: document_processor_service.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor(self, response: processor.Processor) -> processor.Processor: - """Post-rpc interceptor for get_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_type(self, request: document_processor_service.GetProcessorTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_type(self, response: processor_type.ProcessorType) -> processor_type.ProcessorType: - """Post-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_version(self, request: document_processor_service.GetProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_version(self, response: processor.ProcessorVersion) -> processor.ProcessorVersion: - """Post-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_evaluations(self, request: document_processor_service.ListEvaluationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_evaluations(self, response: document_processor_service.ListEvaluationsResponse) -> document_processor_service.ListEvaluationsResponse: - """Post-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processors(self, request: document_processor_service.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processors - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processors(self, response: document_processor_service.ListProcessorsResponse) -> document_processor_service.ListProcessorsResponse: - """Post-rpc interceptor for list_processors - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_types(self, request: document_processor_service.ListProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_types(self, response: document_processor_service.ListProcessorTypesResponse) -> document_processor_service.ListProcessorTypesResponse: - """Post-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_versions(self, request: document_processor_service.ListProcessorVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_versions(self, response: document_processor_service.ListProcessorVersionsResponse) -> document_processor_service.ListProcessorVersionsResponse: - """Post-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_process_document(self, request: document_processor_service.ProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for process_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_process_document(self, response: document_processor_service.ProcessResponse) -> document_processor_service.ProcessResponse: - """Post-rpc interceptor for process_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_review_document(self, request: document_processor_service.ReviewDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ReviewDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for review_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_review_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for review_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_set_default_processor_version(self, request: document_processor_service.SetDefaultProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.SetDefaultProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_set_default_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_train_processor_version(self, request: document_processor_service.TrainProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.TrainProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_train_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_undeploy_processor_version(self, request: document_processor_service.UndeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.UndeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_undeploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - def pre_get_location(self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.Location: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_location(self, response: locations_pb2.GetLocationRequest) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_locations(self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]]) -> locations_pb2.ListLocationsResponse: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_locations(self, response: locations_pb2.ListLocationsRequest) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_cancel_operation(self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]]) -> None: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_cancel_operation(self, response: operations_pb2.CancelOperationRequest) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_operation(self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.Operation: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_operation(self, response: operations_pb2.GetOperationRequest) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_operations(self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.ListOperationsResponse: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_operations(self, response: operations_pb2.ListOperationsRequest) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentProcessorServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentProcessorServiceRestInterceptor - - -class DocumentProcessorServiceRestTransport(DocumentProcessorServiceTransport): - """REST backend transport for DocumentProcessorService. - - Service to call Cloud DocumentAI to process documents - according to the processor's definition. Processors are built - using state-of-the-art Google AI such as natural language, - computer vision, and translation to extract structured - information from unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DocumentProcessorServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentProcessorServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchProcessDocuments(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("BatchProcessDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.BatchProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch process documents method over HTTP. - - Args: - request (~.document_processor_service.BatchProcessRequest): - The request object. Request message for batch process - document method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:batchProcess', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:batchProcess', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_process_documents(request, metadata) - pb_request = document_processor_service.BatchProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_process_documents(resp) - return resp - - class _CreateProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("CreateProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.CreateProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_processor.Processor: - r"""Call the create processor method over HTTP. - - Args: - request (~.document_processor_service.CreateProcessorRequest): - The request object. Request message for create a - processor. Notice this request is sent - to a regionalized backend service, and - if the processor type is not available - on that region, the creation will fail. - - 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: - ~.gcd_processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{parent=projects/*/locations/*}/processors', - 'body': 'processor', - }, - ] - request, metadata = self._interceptor.pre_create_processor(request, metadata) - pb_request = document_processor_service.CreateProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_processor.Processor() - pb_resp = gcd_processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_processor(resp) - return resp - - class _DeleteProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorRequest): - The request object. Request message for the delete - processor method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor(request, metadata) - pb_request = document_processor_service.DeleteProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor(resp) - return resp - - class _DeleteProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor version method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorVersionRequest): - The request object. Request message for the delete - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor_version(request, metadata) - pb_request = document_processor_service.DeleteProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor_version(resp) - return resp - - class _DeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the deploy processor version method over HTTP. - - Args: - request (~.document_processor_service.DeployProcessorVersionRequest): - The request object. Request message for the deploy - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_deploy_processor_version(request, metadata) - pb_request = document_processor_service.DeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_deploy_processor_version(resp) - return resp - - class _DisableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DisableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DisableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the disable processor method over HTTP. - - Args: - request (~.document_processor_service.DisableProcessorRequest): - The request object. Request message for the disable - processor method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:disable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_disable_processor(request, metadata) - pb_request = document_processor_service.DisableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_disable_processor(resp) - return resp - - class _EnableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EnableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EnableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the enable processor method over HTTP. - - Args: - request (~.document_processor_service.EnableProcessorRequest): - The request object. Request message for the enable - processor method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:enable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_enable_processor(request, metadata) - pb_request = document_processor_service.EnableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_enable_processor(resp) - return resp - - class _EvaluateProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EvaluateProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EvaluateProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the evaluate processor - version method over HTTP. - - Args: - request (~.document_processor_service.EvaluateProcessorVersionRequest): - The request object. Evaluates the given ProcessorVersion - against the supplied documents. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_evaluate_processor_version(request, metadata) - pb_request = document_processor_service.EvaluateProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_evaluate_processor_version(resp) - return resp - - class _FetchProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("FetchProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.FetchProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Call the fetch processor types method over HTTP. - - Args: - request (~.document_processor_service.FetchProcessorTypesRequest): - The request object. Request message for fetch processor - types. - - 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: - ~.document_processor_service.FetchProcessorTypesResponse: - Response message for fetch processor - types. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*}:fetchProcessorTypes', - }, - ] - request, metadata = self._interceptor.pre_fetch_processor_types(request, metadata) - pb_request = document_processor_service.FetchProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.FetchProcessorTypesResponse() - pb_resp = document_processor_service.FetchProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_processor_types(resp) - return resp - - class _GetEvaluation(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetEvaluation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetEvaluationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> evaluation.Evaluation: - r"""Call the get evaluation method over HTTP. - - Args: - request (~.document_processor_service.GetEvaluationRequest): - The request object. Retrieves a specific Evaluation. - 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: - ~.evaluation.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_evaluation(request, metadata) - pb_request = document_processor_service.GetEvaluationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = evaluation.Evaluation() - pb_resp = evaluation.Evaluation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_evaluation(resp) - return resp - - class _GetProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.Processor: - r"""Call the get processor method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorRequest): - The request object. Request message for get processor. - 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: - ~.processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor(request, metadata) - pb_request = document_processor_service.GetProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.Processor() - pb_resp = processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor(resp) - return resp - - class _GetProcessorType(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor_type.ProcessorType: - r"""Call the get processor type method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorTypeRequest): - The request object. Request message for get processor. - 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: - ~.processor_type.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processorTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_type(request, metadata) - pb_request = document_processor_service.GetProcessorTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor_type.ProcessorType() - pb_resp = processor_type.ProcessorType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_type(resp) - return resp - - class _GetProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.ProcessorVersion: - r"""Call the get processor version method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorVersionRequest): - The request object. Request message for get processor - version. - - 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: - ~.processor.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pre-trained by Google internally or - up-trained by the customer. At a time, a - processor can only have one default - version version. So the processor's - behavior (when processing documents) is - defined by a default version - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_version(request, metadata) - pb_request = document_processor_service.GetProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.ProcessorVersion() - pb_resp = processor.ProcessorVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_version(resp) - return resp - - class _ListEvaluations(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListEvaluations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListEvaluationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListEvaluationsResponse: - r"""Call the list evaluations method over HTTP. - - Args: - request (~.document_processor_service.ListEvaluationsRequest): - The request object. Retrieves a list of evaluations for a - given ProcessorVersion. - - 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: - ~.document_processor_service.ListEvaluationsResponse: - The response from ListEvaluations. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations', - }, - ] - request, metadata = self._interceptor.pre_list_evaluations(request, metadata) - pb_request = document_processor_service.ListEvaluationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListEvaluationsResponse() - pb_resp = document_processor_service.ListEvaluationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_evaluations(resp) - return resp - - class _ListProcessors(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessors") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorsResponse: - r"""Call the list processors method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorsRequest): - The request object. Request message for list all - processors belongs to a project. - - 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: - ~.document_processor_service.ListProcessorsResponse: - Response message for list processors. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*}/processors', - }, - ] - request, metadata = self._interceptor.pre_list_processors(request, metadata) - pb_request = document_processor_service.ListProcessorsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorsResponse() - pb_resp = document_processor_service.ListProcessorsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processors(resp) - return resp - - class _ListProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorTypesResponse: - r"""Call the list processor types method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorTypesRequest): - The request object. Request message for list processor - types. - - 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: - ~.document_processor_service.ListProcessorTypesResponse: - Response message for list processor - types. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*}/processorTypes', - }, - ] - request, metadata = self._interceptor.pre_list_processor_types(request, metadata) - pb_request = document_processor_service.ListProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorTypesResponse() - pb_resp = document_processor_service.ListProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_types(resp) - return resp - - class _ListProcessorVersions(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorVersionsResponse: - r"""Call the list processor versions method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorVersionsRequest): - The request object. Request message for list all - processor versions belongs to a - processor. - - 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: - ~.document_processor_service.ListProcessorVersionsResponse: - Response message for list processors. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions', - }, - ] - request, metadata = self._interceptor.pre_list_processor_versions(request, metadata) - pb_request = document_processor_service.ListProcessorVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorVersionsResponse() - pb_resp = document_processor_service.ListProcessorVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_versions(resp) - return resp - - class _ProcessDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ProcessDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ProcessResponse: - r"""Call the process document method over HTTP. - - Args: - request (~.document_processor_service.ProcessRequest): - The request object. Request message for the process - document method. - - 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: - ~.document_processor_service.ProcessResponse: - Response message for the process - document method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:process', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:process', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_process_document(request, metadata) - pb_request = document_processor_service.ProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ProcessResponse() - pb_resp = document_processor_service.ProcessResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_process_document(resp) - return resp - - class _ReviewDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ReviewDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ReviewDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the review document method over HTTP. - - Args: - request (~.document_processor_service.ReviewDocumentRequest): - The request object. Request message for review document - method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_review_document(request, metadata) - pb_request = document_processor_service.ReviewDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_review_document(resp) - return resp - - class _SetDefaultProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("SetDefaultProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.SetDefaultProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the set default processor - version method over HTTP. - - Args: - request (~.document_processor_service.SetDefaultProcessorVersionRequest): - The request object. Request message for the set default - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{processor=projects/*/locations/*/processors/*}:setDefaultProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_default_processor_version(request, metadata) - pb_request = document_processor_service.SetDefaultProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_default_processor_version(resp) - return resp - - class _TrainProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("TrainProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.TrainProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the train processor version method over HTTP. - - Args: - request (~.document_processor_service.TrainProcessorVersionRequest): - The request object. Request message for the create - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:train', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_train_processor_version(request, metadata) - pb_request = document_processor_service.TrainProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_train_processor_version(resp) - return resp - - class _UndeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("UndeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.UndeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the undeploy processor - version method over HTTP. - - Args: - request (~.document_processor_service.UndeployProcessorVersionRequest): - The request object. Request message for the undeploy - processor version method. - - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_undeploy_processor_version(request, metadata) - pb_request = document_processor_service.UndeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_undeploy_processor_version(resp) - return resp - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchProcessDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DisableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EnableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EvaluateProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._FetchProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - evaluation.Evaluation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - document_processor_service.ListEvaluationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ProcessDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ReviewDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetDefaultProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TrainProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UndeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*}/locations', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentProcessorServiceRestTransport', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py deleted file mode 100644 index 57f2c6fe..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- 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 .barcode import ( - Barcode, -) -from .document import ( - Document, -) -from .document_io import ( - BatchDocumentsInputConfig, - DocumentOutputConfig, - GcsDocument, - GcsDocuments, - GcsPrefix, - OcrConfig, - RawDocument, -) -from .document_processor_service import ( - BatchProcessMetadata, - BatchProcessRequest, - BatchProcessResponse, - CreateProcessorRequest, - DeleteProcessorMetadata, - DeleteProcessorRequest, - DeleteProcessorVersionMetadata, - DeleteProcessorVersionRequest, - DeployProcessorVersionMetadata, - DeployProcessorVersionRequest, - DeployProcessorVersionResponse, - DisableProcessorMetadata, - DisableProcessorRequest, - DisableProcessorResponse, - EnableProcessorMetadata, - EnableProcessorRequest, - EnableProcessorResponse, - EvaluateProcessorVersionMetadata, - EvaluateProcessorVersionRequest, - EvaluateProcessorVersionResponse, - FetchProcessorTypesRequest, - FetchProcessorTypesResponse, - GetEvaluationRequest, - GetProcessorRequest, - GetProcessorTypeRequest, - GetProcessorVersionRequest, - HumanReviewStatus, - ListEvaluationsRequest, - ListEvaluationsResponse, - ListProcessorsRequest, - ListProcessorsResponse, - ListProcessorTypesRequest, - ListProcessorTypesResponse, - ListProcessorVersionsRequest, - ListProcessorVersionsResponse, - ProcessOptions, - ProcessRequest, - ProcessResponse, - ReviewDocumentOperationMetadata, - ReviewDocumentRequest, - ReviewDocumentResponse, - SetDefaultProcessorVersionMetadata, - SetDefaultProcessorVersionRequest, - SetDefaultProcessorVersionResponse, - TrainProcessorVersionMetadata, - TrainProcessorVersionRequest, - TrainProcessorVersionResponse, - UndeployProcessorVersionMetadata, - UndeployProcessorVersionRequest, - UndeployProcessorVersionResponse, -) -from .document_schema import ( - DocumentSchema, -) -from .evaluation import ( - Evaluation, - EvaluationReference, -) -from .geometry import ( - BoundingPoly, - NormalizedVertex, - Vertex, -) -from .operation_metadata import ( - CommonOperationMetadata, -) -from .processor import ( - Processor, - ProcessorVersion, -) -from .processor_type import ( - ProcessorType, -) - -__all__ = ( - 'Barcode', - 'Document', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'OcrConfig', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessOptions', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorType', -) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py deleted file mode 100644 index 4738df4a..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- 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 - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'Barcode', - }, -) - - -class Barcode(proto.Message): - r"""Encodes the detailed information of a barcode. - - 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. - 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. - raw_value (str): - Raw value encoded in the barcode. For example: - ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. - """ - - format_: str = proto.Field( - proto.STRING, - number=1, - ) - value_format: str = proto.Field( - proto.STRING, - number=2, - ) - raw_value: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py deleted file mode 100644 index 6517064f..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py +++ /dev/null @@ -1,1712 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.cloud.documentai_v1beta3.types import barcode as gcd_barcode -from google.cloud.documentai_v1beta3.types import geometry -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import color_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import money_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'Document', - }, -) - - -class Document(proto.Message): - r"""Document represents the canonical document resource in - Document AI. It is an interchange format that provides insights - into documents and allows for collaboration between users and - Document AI to iterate and optimize for quality. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - uri (str): - Optional. Currently supports Google Cloud Storage URI of the - form ``gs://bucket_name/object_name``. Object versioning is - not supported. See `Google Cloud Storage Request - URIs `__ - for more info. - - This field is a member of `oneof`_ ``source``. - content (bytes): - Optional. Inline document content, represented as a stream - of bytes. Note: As with all ``bytes`` fields, protobuffers - use a pure binary representation, whereas JSON - representations use base64. - - This field is a member of `oneof`_ ``source``. - mime_type (str): - An IANA published MIME type (also referred to - as media type). For more information, see - https://www.iana.org/assignments/media-types/media-types.xhtml. - text (str): - Optional. UTF-8 encoded text in reading order - from the document. - text_styles (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Style]): - Styles for the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - pages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page]): - Visual page layout for the - [Document][google.cloud.documentai.v1beta3.Document]. - entities (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Entity]): - A list of entities detected on - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - For document shards, entities in this list may cross shard - boundaries. - entity_relations (MutableSequence[google.cloud.documentai_v1beta3.types.Document.EntityRelation]): - Placeholder. Relationship among - [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][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. - If the document is not sharded, this message is - not specified. - error (google.rpc.status_pb2.Status): - Any error that occurred while processing this - document. - revisions (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Revision]): - Placeholder. Revision history of this - document. - """ - - class ShardInfo(proto.Message): - r"""For a large document, sharding may be performed to produce - several document shards. Each document shard contains this field - to detail which shard it is. - - Attributes: - shard_index (int): - The 0-based index of this shard. - shard_count (int): - Total number of shards. - text_offset (int): - The index of the first character in - [Document.text][google.cloud.documentai.v1beta3.Document.text] - in the overall document global text. - """ - - shard_index: int = proto.Field( - proto.INT64, - number=1, - ) - shard_count: int = proto.Field( - proto.INT64, - number=2, - ) - text_offset: int = proto.Field( - proto.INT64, - number=3, - ) - - class Style(proto.Message): - r"""Annotation for common text style attributes. This adheres to - CSS conventions as much as possible. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - color (google.type.color_pb2.Color): - Text color. - background_color (google.type.color_pb2.Color): - Text background color. - font_weight (str): - Font weight. Possible values are normal, bold, bolder, and - lighter. https://www.w3schools.com/cssref/pr_font_weight.asp - text_style (str): - Text style. Possible values are normal, italic, and oblique. - https://www.w3schools.com/cssref/pr_font_font-style.asp - text_decoration (str): - Text decoration. Follows CSS standard. - 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): - r"""Font size with unit. - - Attributes: - size (float): - Font size for the text. - unit (str): - Unit for the font size. Follows CSS naming - (in, px, pt, etc.). - """ - - size: float = proto.Field( - proto.FLOAT, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=2, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=3, - message=color_pb2.Color, - ) - font_weight: str = proto.Field( - proto.STRING, - number=4, - ) - text_style: str = proto.Field( - proto.STRING, - number=5, - ) - text_decoration: str = proto.Field( - proto.STRING, - number=6, - ) - font_size: 'Document.Style.FontSize' = proto.Field( - 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]. - - Attributes: - page_number (int): - 1-based index for current - [Page][google.cloud.documentai.v1beta3.Document.Page] in a - parent [Document][google.cloud.documentai.v1beta3.Document]. - Useful when a page is taken out of a - [Document][google.cloud.documentai.v1beta3.Document] for - individual processing. - image (google.cloud.documentai_v1beta3.types.Document.Page.Image): - Rendered image for this page. This image is - preprocessed to remove any skew, rotation, and - distortions such that the annotation bounding - boxes can be upright and axis-aligned. - transforms (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Matrix]): - Transformation matrices that were applied to the original - document image to produce - [Page.image][google.cloud.documentai.v1beta3.Document.Page.image]. - dimension (google.cloud.documentai_v1beta3.types.Document.Page.Dimension): - Physical dimension of the page. - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for the page. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - blocks (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Block]): - A list of visually detected text blocks on - the page. A block has a set of lines (collected - into paragraphs) that have a common line-spacing - and orientation. - paragraphs (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Paragraph]): - A list of visually detected text paragraphs - on the page. A collection of lines that a human - would perceive as a paragraph. - lines (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Line]): - A list of visually detected text lines on the - page. A collection of tokens that a human would - perceive as a line. - tokens (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Token]): - A list of visually detected tokens on the - page. - visual_elements (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.VisualElement]): - A list of detected non-text visual elements - e.g. checkbox, signature etc. on the page. - tables (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table]): - A list of visually detected tables on the - page. - form_fields (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.FormField]): - A list of visually detected form fields on - the page. - symbols (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Symbol]): - A list of visually detected symbols on the - 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. - """ - - class Dimension(proto.Message): - r"""Dimension for the page. - - Attributes: - width (float): - Page width. - height (float): - Page height. - unit (str): - Dimension unit. - """ - - width: float = proto.Field( - proto.FLOAT, - number=1, - ) - height: float = proto.Field( - proto.FLOAT, - number=2, - ) - unit: str = proto.Field( - proto.STRING, - number=3, - ) - - class Image(proto.Message): - r"""Rendered image contents for this page. - - Attributes: - content (bytes): - Raw byte content of the image. - mime_type (str): - Encoding mime type for the image. - width (int): - Width of the image in pixels. - height (int): - Height of the image in pixels. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - width: int = proto.Field( - proto.INT32, - number=3, - ) - height: int = proto.Field( - proto.INT32, - number=4, - ) - - class Matrix(proto.Message): - r"""Representation for transformation matrix, intended to be - compatible and used with OpenCV format for image manipulation. - - Attributes: - rows (int): - Number of rows in the matrix. - cols (int): - Number of columns in the matrix. - type_ (int): - This encodes information about what data type the matrix - uses. For example, 0 (CV_8U) is an unsigned 8-bit image. For - the full list of OpenCV primitive data types, please refer - to - https://docs.opencv.org/4.3.0/d1/d1b/group__core__hal__interface.html - data (bytes): - The matrix data. - """ - - rows: int = proto.Field( - proto.INT32, - number=1, - ) - cols: int = proto.Field( - proto.INT32, - number=2, - ) - type_: int = proto.Field( - proto.INT32, - number=3, - ) - data: bytes = proto.Field( - proto.BYTES, - number=4, - ) - - class Layout(proto.Message): - r"""Visual element describing a layout unit on a page. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - confidence (float): - Confidence of the current - [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]``. - bounding_poly (google.cloud.documentai_v1beta3.types.BoundingPoly): - The bounding polygon for the - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout]. - orientation (google.cloud.documentai_v1beta3.types.Document.Page.Layout.Orientation): - Detected orientation for the - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout]. - """ - class Orientation(proto.Enum): - r"""Detected human reading orientation. - - Values: - ORIENTATION_UNSPECIFIED (0): - Unspecified orientation. - PAGE_UP (1): - Orientation is aligned with page up. - PAGE_RIGHT (2): - Orientation is aligned with page right. - Turn the head 90 degrees clockwise from upright - to read. - PAGE_DOWN (3): - Orientation is aligned with page down. - Turn the head 180 degrees from upright to read. - PAGE_LEFT (4): - Orientation is aligned with page left. - Turn the head 90 degrees counterclockwise from - upright to read. - """ - ORIENTATION_UNSPECIFIED = 0 - PAGE_UP = 1 - PAGE_RIGHT = 2 - PAGE_DOWN = 3 - PAGE_LEFT = 4 - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=3, - message=geometry.BoundingPoly, - ) - orientation: 'Document.Page.Layout.Orientation' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Page.Layout.Orientation', - ) - - class Block(proto.Message): - r"""A block has a set of lines (collected into paragraphs) that - have a common line-spacing and orientation. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Block][google.cloud.documentai.v1beta3.Document.Page.Block]. - 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 annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Paragraph(proto.Message): - r"""A collection of lines that a human would perceive as a - paragraph. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Paragraph][google.cloud.documentai.v1beta3.Document.Page.Paragraph]. - 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 annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Line(proto.Message): - r"""A collection of tokens that a human would perceive as a line. - Does not cross column boundaries, can be horizontal, vertical, - etc. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Line][google.cloud.documentai.v1beta3.Document.Page.Line]. - 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 annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Token(proto.Message): - r"""A detected token. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. - detected_break (google.cloud.documentai_v1beta3.types.Document.Page.Token.DetectedBreak): - Detected break at the end of a - [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. - 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 annotation. - """ - - class DetectedBreak(proto.Message): - r"""Detected break at the end of a - [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. - - Attributes: - type_ (google.cloud.documentai_v1beta3.types.Document.Page.Token.DetectedBreak.Type): - Detected break type. - """ - class Type(proto.Enum): - r"""Enum to denote the type of break found. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified break type. - SPACE (1): - A single whitespace. - WIDE_SPACE (2): - A wider whitespace. - HYPHEN (3): - A hyphen that indicates that a token has been - split across lines. - """ - TYPE_UNSPECIFIED = 0 - SPACE = 1 - WIDE_SPACE = 2 - HYPHEN = 3 - - type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Document.Page.Token.DetectedBreak.Type', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Token.DetectedBreak', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=4, - message='Document.Provenance', - ) - - class Symbol(proto.Message): - r"""A detected symbol. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Symbol][google.cloud.documentai.v1beta3.Document.Page.Symbol]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class VisualElement(proto.Message): - r"""Detected non-text visual elements e.g. checkbox, signature - etc. on the page. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [VisualElement][google.cloud.documentai.v1beta3.Document.Page.VisualElement]. - type_ (str): - Type of the - [VisualElement][google.cloud.documentai.v1beta3.Document.Page.VisualElement]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - - class Table(proto.Message): - r"""A table representation similar to HTML table structure. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Table][google.cloud.documentai.v1beta3.Document.Page.Table]. - header_rows (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): - Header rows of the table. - body_rows (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): - Body rows of the table. - 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): - r"""A row of table cells. - - Attributes: - cells (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableCell]): - Cells that make up this row. - """ - - cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.Page.Table.TableCell', - ) - - class TableCell(proto.Message): - r"""A cell representation inside the table. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [TableCell][google.cloud.documentai.v1beta3.Document.Page.Table.TableCell]. - row_span (int): - How many rows this cell spans. - col_span (int): - How many columns this cell spans. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - row_span: int = proto.Field( - proto.INT32, - number=2, - ) - col_span: int = proto.Field( - proto.INT32, - number=3, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.Table.TableRow', - ) - body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.Table.TableRow', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - 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. - - Attributes: - field_name (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta3.Document.Page.FormField] - name. e.g. ``Address``, ``Email``, ``Grand total``, - ``Phone number``, etc. - field_value (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta3.Document.Page.FormField] - value. - name_detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages for name - together with confidence. - value_detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages for value - together with confidence. - value_type (str): - If the value is non-textual, this field represents the type. - Current valid values are: - - - blank (this indicates the ``field_value`` is normal text) - - ``unfilled_checkbox`` - - ``filled_checkbox`` - corrected_key_text (str): - Created for Labeling UI to export key text. If corrections - were made to the text identified by the - ``field_name.text_anchor``, this field will contain the - correction. - corrected_value_text (str): - Created for Labeling UI to export value text. If corrections - were made to the text identified by the - ``field_value.text_anchor``, this field will contain the - correction. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this annotation. - """ - - field_name: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - field_value: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Layout', - ) - name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - value_type: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_key_text: str = proto.Field( - proto.STRING, - number=6, - ) - corrected_value_text: str = proto.Field( - proto.STRING, - number=7, - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=8, - message='Document.Provenance', - ) - - class DetectedBarcode(proto.Message): - r"""A detected barcode. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [DetectedBarcode][google.cloud.documentai.v1beta3.Document.Page.DetectedBarcode]. - barcode (google.cloud.documentai_v1beta3.types.Barcode): - Detailed barcode information of the - [DetectedBarcode][google.cloud.documentai.v1beta3.Document.Page.DetectedBarcode]. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - barcode: gcd_barcode.Barcode = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_barcode.Barcode, - ) - - class DetectedLanguage(proto.Message): - r"""Detected language for a structural component. - - Attributes: - language_code (str): - 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]``. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - 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, - ) - image: 'Document.Page.Image' = proto.Field( - proto.MESSAGE, - number=13, - message='Document.Page.Image', - ) - transforms: MutableSequence['Document.Page.Matrix'] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='Document.Page.Matrix', - ) - dimension: 'Document.Page.Dimension' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Dimension', - ) - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Document.Page.Block', - ) - paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Document.Page.Paragraph', - ) - lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Document.Page.Line', - ) - tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='Document.Page.Token', - ) - visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Document.Page.VisualElement', - ) - tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Page.Table', - ) - form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='Document.Page.FormField', - ) - symbols: MutableSequence['Document.Page.Symbol'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='Document.Page.Symbol', - ) - detected_barcodes: MutableSequence['Document.Page.DetectedBarcode'] = proto.RepeatedField( - 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, - message='Document.Provenance', - ) - - class Entity(proto.Message): - r"""An entity that could be a phrase in the text or a property - that belongs to the document. It is a known entity type, such as - a person, an organization, or location. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Optional. Provenance of the entity. Text anchor indexing - into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - type_ (str): - Required. Entity type from a schema e.g. ``Address``. - mention_text (str): - 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]``. - page_anchor (google.cloud.documentai_v1beta3.types.Document.PageAnchor): - Optional. Represents the provenance of this - entity wrt. the location on the page where it - was found. - id (str): - Optional. Canonical id. This will be a unique - value in the entity list for this document. - normalized_value (google.cloud.documentai_v1beta3.types.Document.Entity.NormalizedValue): - Optional. Normalized entity value. Absent if - the extracted value could not be converted or - the type (e.g. address) is not supported for - certain parsers. This field is also only - populated for certain supported document types. - properties (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Entity]): - Optional. Entities can be nested to form a - hierarchical data structure representing the - content in the document. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - Optional. The history of this annotation. - redacted (bool): - Optional. Whether the entity will be redacted - for de-identification purposes. - """ - - class NormalizedValue(proto.Message): - r"""Parsed and normalized entity value. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - money_value (google.type.money_pb2.Money): - Money value. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/money.proto - - This field is a member of `oneof`_ ``structured_value``. - date_value (google.type.date_pb2.Date): - Date value. Includes year, month, day. See - also: - https://github.com/googleapis/googleapis/blob/master/google/type/date.proto - - This field is a member of `oneof`_ ``structured_value``. - datetime_value (google.type.datetime_pb2.DateTime): - DateTime value. Includes date, time, and - timezone. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/datetime.proto - - This field is a member of `oneof`_ ``structured_value``. - address_value (google.type.postal_address_pb2.PostalAddress): - Postal address. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/postal_address.proto - - This field is a member of `oneof`_ ``structured_value``. - boolean_value (bool): - Boolean value. Can be used for entities with - binary values, or for checkboxes. - - This field is a member of `oneof`_ ``structured_value``. - integer_value (int): - Integer value. - - This field is a member of `oneof`_ ``structured_value``. - float_value (float): - Float value. - - This field is a member of `oneof`_ ``structured_value``. - text (str): - Optional. An optional field to store a normalized string. - For some entity types, one of respective - ``structured_value`` fields may also be populated. Also not - all the types of ``structured_value`` will be normalized. - For example, some processors may not generate ``float`` or - ``integer`` normalized text by default. - - Below are sample formats mapped to structured values. - - - Money/Currency type (``money_value``) is in the ISO 4217 - text format. - - Date type (``date_value``) is in the ISO 8601 text - format. - - Datetime type (``datetime_value``) is in the ISO 8601 - text format. - """ - - money_value: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - oneof='structured_value', - message=money_pb2.Money, - ) - date_value: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - oneof='structured_value', - message=date_pb2.Date, - ) - datetime_value: datetime_pb2.DateTime = proto.Field( - proto.MESSAGE, - number=4, - oneof='structured_value', - message=datetime_pb2.DateTime, - ) - address_value: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=5, - oneof='structured_value', - message=postal_address_pb2.PostalAddress, - ) - boolean_value: bool = proto.Field( - proto.BOOL, - number=6, - oneof='structured_value', - ) - integer_value: int = proto.Field( - proto.INT32, - number=7, - oneof='structured_value', - ) - float_value: float = proto.Field( - proto.FLOAT, - number=8, - oneof='structured_value', - ) - text: str = proto.Field( - proto.STRING, - number=1, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - mention_text: str = proto.Field( - proto.STRING, - number=3, - ) - mention_id: str = proto.Field( - proto.STRING, - number=4, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - page_anchor: 'Document.PageAnchor' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.PageAnchor', - ) - id: str = proto.Field( - proto.STRING, - number=7, - ) - normalized_value: 'Document.Entity.NormalizedValue' = proto.Field( - proto.MESSAGE, - number=9, - message='Document.Entity.NormalizedValue', - ) - properties: MutableSequence['Document.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Entity', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=11, - message='Document.Provenance', - ) - redacted: bool = proto.Field( - proto.BOOL, - number=12, - ) - - class EntityRelation(proto.Message): - r"""Relationship between - [Entities][google.cloud.documentai.v1beta3.Document.Entity]. - - Attributes: - subject_id (str): - Subject entity id. - object_id (str): - Object entity id. - relation (str): - Relationship description. - """ - - subject_id: str = proto.Field( - proto.STRING, - number=1, - ) - object_id: str = proto.Field( - proto.STRING, - number=2, - ) - relation: str = proto.Field( - proto.STRING, - number=3, - ) - - class TextAnchor(proto.Message): - r"""Text reference indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - - Attributes: - text_segments (MutableSequence[google.cloud.documentai_v1beta3.types.Document.TextAnchor.TextSegment]): - The text segments from the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - content (str): - Contains the content of the text span so that users do not - have to look it up in the text_segments. It is always - populated for formFields. - """ - - class TextSegment(proto.Message): - r"""A text segment in the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. The - indices may be out of bounds which indicate that the text extends - into another document shard for large sharded documents. See - [ShardInfo.text_offset][google.cloud.documentai.v1beta3.Document.ShardInfo.text_offset] - - Attributes: - start_index (int): - [TextSegment][google.cloud.documentai.v1beta3.Document.TextAnchor.TextSegment] - start UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - end_index (int): - [TextSegment][google.cloud.documentai.v1beta3.Document.TextAnchor.TextSegment] - half open end UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - """ - - start_index: int = proto.Field( - proto.INT64, - number=1, - ) - end_index: int = proto.Field( - proto.INT64, - number=2, - ) - - text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.TextAnchor.TextSegment', - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class PageAnchor(proto.Message): - r"""Referencing the visual context of the entity in the - [Document.pages][google.cloud.documentai.v1beta3.Document.pages]. - Page anchors can be cross-page, consist of multiple bounding - polygons and optionally reference specific layout element types. - - Attributes: - page_refs (MutableSequence[google.cloud.documentai_v1beta3.types.Document.PageAnchor.PageRef]): - One or more references to visual page - elements - """ - - class PageRef(proto.Message): - r"""Represents a weak reference to a page element within a - document. - - Attributes: - page (int): - Required. Index into the - [Document.pages][google.cloud.documentai.v1beta3.Document.pages] - element, for example using - ``[Document.pages][page_refs.page]`` to locate the related - page element. This field is skipped when its value is the - default ``0``. See - https://developers.google.com/protocol-buffers/docs/proto3#json. - layout_type (google.cloud.documentai_v1beta3.types.Document.PageAnchor.PageRef.LayoutType): - Optional. The type of the layout element that - is being referenced if any. - layout_id (str): - Optional. Deprecated. Use - [PageRef.bounding_poly][google.cloud.documentai.v1beta3.Document.PageAnchor.PageRef.bounding_poly] - instead. - bounding_poly (google.cloud.documentai_v1beta3.types.BoundingPoly): - Optional. Identifies the bounding polygon of - a layout element on the page. - confidence (float): - Optional. Confidence of detected page element, if - applicable. Range ``[0, 1]``. - """ - class LayoutType(proto.Enum): - r"""The type of layout that is being referenced. - - Values: - LAYOUT_TYPE_UNSPECIFIED (0): - Layout Unspecified. - BLOCK (1): - References a - [Page.blocks][google.cloud.documentai.v1beta3.Document.Page.blocks] - element. - PARAGRAPH (2): - References a - [Page.paragraphs][google.cloud.documentai.v1beta3.Document.Page.paragraphs] - element. - LINE (3): - References a - [Page.lines][google.cloud.documentai.v1beta3.Document.Page.lines] - element. - TOKEN (4): - References a - [Page.tokens][google.cloud.documentai.v1beta3.Document.Page.tokens] - element. - VISUAL_ELEMENT (5): - References a - [Page.visual_elements][google.cloud.documentai.v1beta3.Document.Page.visual_elements] - element. - TABLE (6): - Refrrences a - [Page.tables][google.cloud.documentai.v1beta3.Document.Page.tables] - element. - FORM_FIELD (7): - References a - [Page.form_fields][google.cloud.documentai.v1beta3.Document.Page.form_fields] - element. - """ - LAYOUT_TYPE_UNSPECIFIED = 0 - BLOCK = 1 - PARAGRAPH = 2 - LINE = 3 - TOKEN = 4 - VISUAL_ELEMENT = 5 - TABLE = 6 - FORM_FIELD = 7 - - page: int = proto.Field( - proto.INT64, - number=1, - ) - layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( - proto.ENUM, - number=2, - enum='Document.PageAnchor.PageRef.LayoutType', - ) - layout_id: str = proto.Field( - proto.STRING, - number=3, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=4, - message=geometry.BoundingPoly, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - - page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.PageAnchor.PageRef', - ) - - class Provenance(proto.Message): - r"""Structure to identify provenance relationships between - annotations in different revisions. - - Attributes: - revision (int): - The index of the revision that produced this - element. - id (int): - The Id of this operation. Needs to be unique - within the scope of the revision. - parents (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Provenance.Parent]): - References to the original elements that are - replaced. - type_ (google.cloud.documentai_v1beta3.types.Document.Provenance.OperationType): - The type of provenance operation. - """ - class OperationType(proto.Enum): - r"""If a processor or agent does an explicit operation on - existing elements. - - Values: - OPERATION_TYPE_UNSPECIFIED (0): - Operation type unspecified. If no operation is specified a - provenance entry is simply used to match against a - ``parent``. - ADD (1): - Add an element. - REMOVE (2): - Remove an element identified by ``parent``. - UPDATE (7): - Updates any fields within the given - provenance scope of the message. It 'overwrites' - the fields rather than replacing them. This is - especially relevant when we just want to update - a field value of an entity without also - affecting all the child properties. - REPLACE (3): - Currently unused. Replace an element identified by - ``parent``. - EVAL_REQUESTED (4): - Deprecated. Request human review for the element identified - by ``parent``. - EVAL_APPROVED (5): - Deprecated. Element is reviewed and approved - at human review, confidence will be set to 1.0. - EVAL_SKIPPED (6): - Deprecated. Element is skipped in the - validation process. - """ - OPERATION_TYPE_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - UPDATE = 7 - REPLACE = 3 - EVAL_REQUESTED = 4 - EVAL_APPROVED = 5 - EVAL_SKIPPED = 6 - - class Parent(proto.Message): - r"""The parent element the current element is based on. Used for - referencing/aligning, removal and replacement operations. - - Attributes: - revision (int): - The index of the index into current revision's parent_ids - list. - index (int): - The index of the parent item in the - corresponding item list (eg. list of entities, - properties within entities, etc.) in the parent - revision. - id (int): - The id of the parent provenance. - """ - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - index: int = proto.Field( - proto.INT32, - number=3, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - parents: MutableSequence['Document.Provenance.Parent'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance.Parent', - ) - type_: 'Document.Provenance.OperationType' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Provenance.OperationType', - ) - - class Revision(proto.Message): - r"""Contains past or forward revisions of this document. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - agent (str): - If the change was made by a person specify - the name or id of that person. - - This field is a member of `oneof`_ ``source``. - processor (str): - If the annotation was made by processor - identify the processor by its resource name. - - This field is a member of `oneof`_ ``source``. - id (str): - Id of the revision, internally generated by - doc proto storage. Unique within the context of - the document. - parent (MutableSequence[int]): - The revisions that this revision is based on. This can - include one or more parent (when documents are merged.) This - field represents the index into the ``revisions`` field. - parent_ids (MutableSequence[str]): - The revisions that this revision is based on. Must include - all the ids that have anything to do with this revision - - eg. there are ``provenance.parent.revision`` fields that - index into this field. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the revision was created, - internally generated by doc proto storage at the - time of create. - human_review (google.cloud.documentai_v1beta3.types.Document.Revision.HumanReview): - Human Review information of this revision. - """ - - class HumanReview(proto.Message): - r"""Human Review information of the document. - - Attributes: - state (str): - Human review state. e.g. ``requested``, ``succeeded``, - ``rejected``. - state_message (str): - A message providing more details about the current state of - processing. For example, the rejection reason when the state - is ``rejected``. - """ - - state: str = proto.Field( - proto.STRING, - number=1, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - - agent: str = proto.Field( - proto.STRING, - number=4, - oneof='source', - ) - processor: str = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - id: str = proto.Field( - proto.STRING, - number=1, - ) - parent: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=2, - ) - parent_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - human_review: 'Document.Revision.HumanReview' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.Revision.HumanReview', - ) - - class TextChange(proto.Message): - r"""This message is used for text changes aka. OCR corrections. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Provenance of the correction. Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - There can only be a single ``TextAnchor.text_segments`` - element. If the start and end index of the text segment are - the same, the text change is inserted before that index. - changed_text (str): - The text that replaces the text identified in the - ``text_anchor``. - provenance (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Provenance]): - The history of this annotation. - """ - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - changed_text: str = proto.Field( - proto.STRING, - number=2, - ) - provenance: MutableSequence['Document.Provenance'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - text: str = proto.Field( - proto.STRING, - number=4, - ) - text_styles: MutableSequence[Style] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Style, - ) - pages: MutableSequence[Page] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Page, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Entity, - ) - entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=EntityRelation, - ) - text_changes: MutableSequence[TextChange] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=TextChange, - ) - shard_info: ShardInfo = proto.Field( - proto.MESSAGE, - number=9, - message=ShardInfo, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - revisions: MutableSequence[Revision] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Revision, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py deleted file mode 100644 index e194eeb2..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py +++ /dev/null @@ -1,245 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'RawDocument', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'OcrConfig', - }, -) - - -class RawDocument(proto.Message): - r"""Payload message of raw document content (bytes). - - Attributes: - content (bytes): - Inline document content. - mime_type (str): - An IANA MIME type (RFC6838) indicating the nature and format - of the - [content][google.cloud.documentai.v1beta3.RawDocument.content]. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GcsDocument(proto.Message): - r"""Specifies a document stored on Cloud Storage. - - Attributes: - gcs_uri (str): - The Cloud Storage object uri. - mime_type (str): - An IANA MIME type (RFC6838) of the content. - """ - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GcsDocuments(proto.Message): - r"""Specifies a set of documents on Cloud Storage. - - Attributes: - documents (MutableSequence[google.cloud.documentai_v1beta3.types.GcsDocument]): - The list of documents. - """ - - documents: MutableSequence['GcsDocument'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GcsDocument', - ) - - -class GcsPrefix(proto.Message): - r"""Specifies all documents on Cloud Storage with a common - prefix. - - Attributes: - gcs_uri_prefix (str): - The URI prefix. - """ - - gcs_uri_prefix: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchDocumentsInputConfig(proto.Message): - r"""The common config to specify a set of documents used as - input. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (google.cloud.documentai_v1beta3.types.GcsPrefix): - The set of documents that match the specified Cloud Storage - ``gcs_prefix``. - - This field is a member of `oneof`_ ``source``. - gcs_documents (google.cloud.documentai_v1beta3.types.GcsDocuments): - The set of documents individually specified - on Cloud Storage. - - This field is a member of `oneof`_ ``source``. - """ - - gcs_prefix: 'GcsPrefix' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsPrefix', - ) - gcs_documents: 'GcsDocuments' = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsDocuments', - ) - - -class DocumentOutputConfig(proto.Message): - r"""Config that controls the output of documents. All documents - will be written as a JSON file. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_output_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig.GcsOutputConfig): - Output config to write the results to Cloud - Storage. - - This field is a member of `oneof`_ ``destination``. - """ - - class GcsOutputConfig(proto.Message): - r"""The configuration used when outputting documents. - - Attributes: - gcs_uri (str): - The Cloud Storage uri (a directory) of the - output. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies which fields to include in the output documents. - Only supports top level document and pages field so it must - be in the form of ``{document_field_name}`` or - ``pages.{page_field_name}``. - sharding_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig.GcsOutputConfig.ShardingConfig): - Specifies the sharding config for the output - document. - """ - - class ShardingConfig(proto.Message): - r"""The sharding config for the output document. - - Attributes: - pages_per_shard (int): - The number of pages per shard. - pages_overlap (int): - The number of overlapping pages between - consecutive shards. - """ - - pages_per_shard: int = proto.Field( - proto.INT32, - number=1, - ) - pages_overlap: int = proto.Field( - proto.INT32, - number=2, - ) - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - sharding_config: 'DocumentOutputConfig.GcsOutputConfig.ShardingConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='DocumentOutputConfig.GcsOutputConfig.ShardingConfig', - ) - - gcs_output_config: GcsOutputConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message=GcsOutputConfig, - ) - - -class OcrConfig(proto.Message): - r"""Config for Document OCR. - - Attributes: - enable_native_pdf_parsing (bool): - Enables special handling for PDFs with - existing text information. Results in better - text extraction quality in such PDF inputs. - advanced_ocr_options (MutableSequence[str]): - A list of advanced OCR options to further - fine-tune OCR behavior. - """ - - enable_native_pdf_parsing: bool = proto.Field( - proto.BOOL, - number=3, - ) - advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py deleted file mode 100644 index dd08b224..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py +++ /dev/null @@ -1,1534 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -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 document_schema as gcd_document_schema -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 -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'ProcessOptions', - 'ProcessRequest', - 'HumanReviewStatus', - 'ProcessResponse', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'BatchProcessMetadata', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'GetProcessorTypeRequest', - 'GetProcessorRequest', - 'GetProcessorVersionRequest', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'DeleteProcessorVersionRequest', - 'DeleteProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'CreateProcessorRequest', - 'DeleteProcessorRequest', - 'DeleteProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EnableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'DisableProcessorMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'SetDefaultProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'ReviewDocumentOperationMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionResponse', - 'GetEvaluationRequest', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - }, -) - - -class ProcessOptions(proto.Message): - r"""Options for Process API - - Attributes: - ocr_config (google.cloud.documentai_v1beta3.types.OcrConfig): - Only applicable to "Document OCR Processor". - Returns error if set on other processor types. - """ - - ocr_config: document_io.OcrConfig = proto.Field( - proto.MESSAGE, - number=1, - message=document_io.OcrConfig, - ) - - -class ProcessRequest(proto.Message): - r"""Request message for the process document method. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - inline_document (google.cloud.documentai_v1beta3.types.Document): - An inline document proto. - - This field is a member of `oneof`_ ``source``. - raw_document (google.cloud.documentai_v1beta3.types.RawDocument): - A raw document content (bytes). - - This field is a member of `oneof`_ ``source``. - name (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1beta3.Processor] or - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to use for processing. If a - [Processor][google.cloud.documentai.v1beta3.Processor] is - specified, the server will use its [default - version][google.cloud.documentai.v1beta3.Processor.default_processor_version]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - document (google.cloud.documentai_v1beta3.types.Document): - The document payload, the [content] and [mime_type] fields - must be set. - skip_human_review (bool): - 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. Only supports top level document and pages field - so it must be in the form of ``{document_field_name}`` or - ``pages.{page_field_name}``. - process_options (google.cloud.documentai_v1beta3.types.ProcessOptions): - Inference-time options for the process API - """ - - inline_document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - raw_document: document_io.RawDocument = proto.Field( - proto.MESSAGE, - number=5, - oneof='source', - message=document_io.RawDocument, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=3, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=6, - message=field_mask_pb2.FieldMask, - ) - process_options: 'ProcessOptions' = proto.Field( - proto.MESSAGE, - number=7, - message='ProcessOptions', - ) - - -class HumanReviewStatus(proto.Message): - r"""The status of human review on a processed document. - - Attributes: - state (google.cloud.documentai_v1beta3.types.HumanReviewStatus.State): - The state of human review on the processing - request. - state_message (str): - A message providing more details about the - human review state. - human_review_operation (str): - The name of the operation triggered by the processed - document. This field is populated only when the [state] is - [HUMAN_REVIEW_IN_PROGRESS]. It has the same response type - and metadata as the long running operation returned by - [ReviewDocument] method. - """ - class State(proto.Enum): - r"""The final state of human review on a processed document. - - Values: - STATE_UNSPECIFIED (0): - Human review state is unspecified. Most - likely due to an internal error. - SKIPPED (1): - Human review is skipped for the document. - This can happen because human review is not - enabled on the processor or the processing - request has been set to skip this document. - VALIDATION_PASSED (2): - Human review validation is triggered and - passed, so no review is needed. - IN_PROGRESS (3): - Human review validation is triggered and the - document is under review. - ERROR (4): - Some error happened during triggering human review, see the - [state_message] for details. - """ - STATE_UNSPECIFIED = 0 - SKIPPED = 1 - VALIDATION_PASSED = 2 - IN_PROGRESS = 3 - ERROR = 4 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ProcessResponse(proto.Message): - r"""Response message for the process document method. - - Attributes: - document (google.cloud.documentai_v1beta3.types.Document): - The document payload, will populate fields - based on the processor's behavior. - human_review_operation (str): - The name of the operation triggered by the - processed document. If the human review process - is not triggered, this field will be empty. It - has the same response type and metadata as the - long running operation returned by - ReviewDocument method. - human_review_status (google.cloud.documentai_v1beta3.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=2, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='HumanReviewStatus', - ) - - -class BatchProcessRequest(proto.Message): - r"""Request message for batch process document method. - - Attributes: - name (str): - Required. The resource name of - [Processor][google.cloud.documentai.v1beta3.Processor] or - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - input_configs (MutableSequence[google.cloud.documentai_v1beta3.types.BatchProcessRequest.BatchInputConfig]): - The input config for each single document in - the batch process. - output_config (google.cloud.documentai_v1beta3.types.BatchProcessRequest.BatchOutputConfig): - The overall output config for batch process. - input_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): - The input documents for batch process. - document_output_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig): - The overall output config for batch process. - skip_human_review (bool): - Whether Human Review feature should be - skipped for this request. Default to false. - process_options (google.cloud.documentai_v1beta3.types.ProcessOptions): - Inference-time options for the process API - """ - - class BatchInputConfig(proto.Message): - r"""The message for input config in batch process. - - Attributes: - gcs_source (str): - The Cloud Storage location as the source of - the document. - mime_type (str): - Mimetype of the input. If the input is a raw document, the - supported mimetypes are application/pdf, image/tiff, and - image/gif. If the input is a [Document] proto, the type - should be application/json. - """ - - gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - class BatchOutputConfig(proto.Message): - r"""The message for output config in batch process. - - Attributes: - gcs_destination (str): - The output Cloud Storage directory to put the - processed documents. - """ - - gcs_destination: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - input_configs: MutableSequence[BatchInputConfig] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=BatchInputConfig, - ) - output_config: BatchOutputConfig = proto.Field( - proto.MESSAGE, - number=3, - message=BatchOutputConfig, - ) - input_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=5, - message=document_io.BatchDocumentsInputConfig, - ) - document_output_config: document_io.DocumentOutputConfig = proto.Field( - proto.MESSAGE, - number=6, - message=document_io.DocumentOutputConfig, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=4, - ) - process_options: 'ProcessOptions' = proto.Field( - proto.MESSAGE, - number=7, - message='ProcessOptions', - ) - - -class BatchProcessResponse(proto.Message): - r"""Response message for batch process document method. - """ - - -class BatchProcessMetadata(proto.Message): - r"""The long running operation metadata for batch process method. - - Attributes: - state (google.cloud.documentai_v1beta3.types.BatchProcessMetadata.State): - The state of the current batch processing. - state_message (str): - A message providing more details about the - current state of processing. For example, the - error message if the operation is failed. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - individual_process_statuses (MutableSequence[google.cloud.documentai_v1beta3.types.BatchProcessMetadata.IndividualProcessStatus]): - The list of response details of each - document. - """ - class State(proto.Enum): - r"""Possible states of the batch processing operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - WAITING (1): - Request operation is waiting for scheduling. - RUNNING (2): - Request is being processed. - SUCCEEDED (3): - The batch processing completed successfully. - CANCELLING (4): - The batch processing was being cancelled. - CANCELLED (5): - The batch processing was cancelled. - FAILED (6): - The batch processing has failed. - """ - STATE_UNSPECIFIED = 0 - WAITING = 1 - RUNNING = 2 - SUCCEEDED = 3 - CANCELLING = 4 - CANCELLED = 5 - FAILED = 6 - - class IndividualProcessStatus(proto.Message): - r"""The status of a each individual document in the batch - process. - - Attributes: - input_gcs_source (str): - The source of the document, same as the [input_gcs_source] - field in the request when the batch process started. The - batch process is started by take snapshot of that document, - since a user can move or change that document during the - process. - status (google.rpc.status_pb2.Status): - The status processing the document. - output_gcs_destination (str): - The output_gcs_destination (in the request as - ``output_gcs_destination``) of the processed document if it - was successful, otherwise empty. - human_review_operation (str): - The name of the operation triggered by the - processed document. If the human review process - is not triggered, this field will be empty. It - has the same response type and metadata as the - long running operation returned by - ReviewDocument method. - human_review_status (google.cloud.documentai_v1beta3.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - input_gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - output_gcs_destination: str = proto.Field( - proto.STRING, - number=3, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=4, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=5, - message='HumanReviewStatus', - ) - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - individual_process_statuses: MutableSequence[IndividualProcessStatus] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=IndividualProcessStatus, - ) - - -class FetchProcessorTypesRequest(proto.Message): - r"""Request message for fetch processor types. - - Attributes: - parent (str): - Required. The project of processor type to list. The - available processor types may depend on the allow-listing on - projects. Format: - ``projects/{project}/locations/{location}`` - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FetchProcessorTypesResponse(proto.Message): - r"""Response message for fetch processor types. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType]): - The list of processor types. - """ - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - - -class ListProcessorTypesRequest(proto.Message): - r"""Request message for list processor types. - - Attributes: - parent (str): - Required. The location of processor type to list. The - available processor types may depend on the allow-listing on - projects. Format: - ``projects/{project}/locations/{location}`` - page_size (int): - The maximum number of processor types to - return. If unspecified, at most 100 processor - types will be returned. The maximum value is - 500; values above 500 will be coerced to 500. - page_token (str): - Used to retrieve the next page of results, - empty if at the end of the list. - """ - - 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 ListProcessorTypesResponse(proto.Message): - r"""Response message for list processor types. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType]): - The processor types. - next_page_token (str): - Points to the next page, otherwise empty. - """ - - @property - def raw_page(self): - return self - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListProcessorsRequest(proto.Message): - r"""Request message for list all processors belongs to a project. - - Attributes: - parent (str): - Required. The parent (project and location) which owns this - collection of Processors. Format: - ``projects/{project}/locations/{location}`` - page_size (int): - The maximum number of processors to return. - If unspecified, at most 50 processors will be - returned. The maximum value is 100; values above - 100 will be coerced to 100. - page_token (str): - We will return the processors sorted by - creation time. The page token will point to the - next processor. - """ - - 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 ListProcessorsResponse(proto.Message): - r"""Response message for list processors. - - Attributes: - processors (MutableSequence[google.cloud.documentai_v1beta3.types.Processor]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processors: MutableSequence[gcd_processor.Processor] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.Processor, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetProcessorTypeRequest(proto.Message): - r"""Request message for get processor. - - Attributes: - name (str): - Required. The processor type resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorRequest(proto.Message): - r"""Request message for get processor. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorVersionRequest(proto.Message): - r"""Request message for get processor version. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProcessorVersionsRequest(proto.Message): - r"""Request message for list all processor versions belongs to a - processor. - - Attributes: - parent (str): - Required. The parent (project, location and processor) to - list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - page_size (int): - The maximum number of processor versions to - return. If unspecified, at most 10 processor - versions will be returned. The maximum value is - 20; values above 20 will be coerced to 20. - page_token (str): - We will return the processor versions sorted - by creation time. The page token will point to - the next processor version. - """ - - 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 ListProcessorVersionsResponse(proto.Message): - r"""Response message for list processors. - - Attributes: - processor_versions (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorVersion]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processor_versions: MutableSequence[gcd_processor.ProcessorVersion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.ProcessorVersion, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteProcessorVersionRequest(proto.Message): - r"""Request message for the delete processor version method. - - Attributes: - name (str): - Required. The processor version resource name - to be deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for delete processor - version 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 DeployProcessorVersionRequest(proto.Message): - r"""Request message for the deploy processor version method. - - Attributes: - name (str): - Required. The processor version resource name - to be deployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeployProcessorVersionResponse(proto.Message): - r"""Response message for the deploy processor version method. - """ - - -class DeployProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for deploy processor - version 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 UndeployProcessorVersionRequest(proto.Message): - r"""Request message for the undeploy processor version method. - - Attributes: - name (str): - Required. The processor version resource name - to be undeployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeployProcessorVersionResponse(proto.Message): - r"""Response message for the undeploy processor version method. - """ - - -class UndeployProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for the undeploy - processor version 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 CreateProcessorRequest(proto.Message): - r"""Request message for create a processor. Notice this request - is sent to a regionalized backend service, and if the processor - type is not available on that region, the creation will fail. - - Attributes: - parent (str): - Required. The parent (project and location) under which to - create the processor. Format: - ``projects/{project}/locations/{location}`` - processor (google.cloud.documentai_v1beta3.types.Processor): - Required. The processor to be created, requires - [processor_type] and [display_name] to be set. Also, the - processor is under CMEK if CMEK fields are set. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - processor: gcd_processor.Processor = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_processor.Processor, - ) - - -class DeleteProcessorRequest(proto.Message): - r"""Request message for the delete processor method. - - Attributes: - name (str): - Required. The processor resource name to be - deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorMetadata(proto.Message): - r"""The long running operation metadata for delete processor - 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=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class EnableProcessorRequest(proto.Message): - r"""Request message for the enable processor method. - - Attributes: - name (str): - Required. The processor resource name to be - enabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EnableProcessorResponse(proto.Message): - r"""Response message for the enable processor method. - Intentionally empty proto for adding fields in future. - - """ - - -class EnableProcessorMetadata(proto.Message): - r"""The long running operation metadata for enable processor - 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=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class DisableProcessorRequest(proto.Message): - r"""Request message for the disable processor method. - - Attributes: - name (str): - Required. The processor resource name to be - disabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DisableProcessorResponse(proto.Message): - r"""Response message for the disable processor method. - Intentionally empty proto for adding fields in future. - - """ - - -class DisableProcessorMetadata(proto.Message): - r"""The long running operation metadata for disable processor - 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=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class SetDefaultProcessorVersionRequest(proto.Message): - r"""Request message for the set default processor version method. - - Attributes: - processor (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1beta3.Processor] to - change default version. - default_processor_version (str): - Required. The resource name of child - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to use as default. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{version}`` - """ - - processor: str = proto.Field( - proto.STRING, - number=1, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SetDefaultProcessorVersionResponse(proto.Message): - r"""Response message for set default processor version method. - """ - - -class SetDefaultProcessorVersionMetadata(proto.Message): - r"""The long running operation metadata for set default processor - version 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 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. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - inline_document (google.cloud.documentai_v1beta3.types.Document): - An inline document proto. - - This field is a member of `oneof`_ ``source``. - human_review_config (str): - Required. The resource name of the - HumanReviewConfig that the document will be - reviewed with. - document (google.cloud.documentai_v1beta3.types.Document): - The document that needs human review. - enable_schema_validation (bool): - Whether the validation should be performed on - the ad-hoc review request. - priority (google.cloud.documentai_v1beta3.types.ReviewDocumentRequest.Priority): - The priority of the human review task. - document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): - The document schema of the human review task. - """ - class Priority(proto.Enum): - r"""The priority level of the human review task. - - Values: - DEFAULT (0): - The default priority level. - URGENT (1): - The urgent priority level. The labeling - manager should allocate labeler resource to the - urgent task queue to respect this priority - level. - """ - DEFAULT = 0 - URGENT = 1 - - inline_document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - human_review_config: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - enable_schema_validation: bool = proto.Field( - proto.BOOL, - number=3, - ) - priority: Priority = proto.Field( - proto.ENUM, - number=5, - enum=Priority, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_document_schema.DocumentSchema, - ) - - -class ReviewDocumentResponse(proto.Message): - r"""Response message for review document method. - - Attributes: - gcs_destination (str): - The Cloud Storage uri for the human reviewed - document if the review is succeeded. - state (google.cloud.documentai_v1beta3.types.ReviewDocumentResponse.State): - The state of the review operation. - rejection_reason (str): - The reason why the review is rejected by - reviewer. - """ - class State(proto.Enum): - r"""Possible states of the review operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - REJECTED (1): - The review operation is rejected by the - reviewer. - SUCCEEDED (2): - The review operation is succeeded. - """ - STATE_UNSPECIFIED = 0 - REJECTED = 1 - SUCCEEDED = 2 - - gcs_destination: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - rejection_reason: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ReviewDocumentOperationMetadata(proto.Message): - r"""The long running operation metadata for review document - method. - - Attributes: - state (google.cloud.documentai_v1beta3.types.ReviewDocumentOperationMetadata.State): - Used only when Operation.done is false. - state_message (str): - A message providing more details about the - current state of processing. For example, the - error message if the operation is failed. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long running - operation. - question_id (str): - The Crowd Compute question ID. - """ - class State(proto.Enum): - r"""State of the longrunning operation. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - RUNNING (1): - Operation is still running. - CANCELLING (2): - Operation is being cancelled. - SUCCEEDED (3): - Operation succeeded. - FAILED (4): - Operation failed. - CANCELLED (5): - Operation is cancelled. - """ - STATE_UNSPECIFIED = 0 - RUNNING = 1 - CANCELLING = 2 - SUCCEEDED = 3 - FAILED = 4 - CANCELLED = 5 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - question_id: str = proto.Field( - proto.STRING, - number=6, - ) - - -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/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py deleted file mode 100644 index 6b54cede..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py +++ /dev/null @@ -1,242 +0,0 @@ -# -*- 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 - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'DocumentSchema', - }, -) - - -class DocumentSchema(proto.Message): - r"""The schema defines the output of the processed document by a - processor. - - Attributes: - display_name (str): - Display name to show to users. - description (str): - Description of the schema. - entity_types (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType]): - Entity types of the schema. - metadata (google.cloud.documentai_v1beta3.types.DocumentSchema.Metadata): - Metadata of the schema. - """ - - class EntityType(proto.Message): - r"""EntityType is the wrapper of a label of the corresponding - model with detailed attributes and limitations for entity-based - processors. Multiple types can also compose a dependency tree to - represent nested types. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - enum_values (google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.EnumValues): - If specified, lists all the possible values for this entity. - This should not be more than a handful of values. If the - number of values is >10 or could change frequently use the - ``EntityType.value_ontology`` field and specify a list of - all possible values in a value ontology file. - - This field is a member of `oneof`_ ``value_source``. - display_name (str): - User defined name for the type. - name (str): - Name of the type. It must be unique within the schema file - and cannot be a 'Common Type'. Besides that we use the - following naming conventions: - - - *use ``snake_casing``* - - name matching is case-sensitive - - 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 - compatibility. - base_types (MutableSequence[str]): - The entity type that this type is derived - from. For now, one and only one should be set. - properties (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.Property]): - Describing the nested structure, or - composition of an entity. - """ - - class EnumValues(proto.Message): - r"""Defines the a list of enum values. - - Attributes: - values (MutableSequence[str]): - The individual values that this enum values - type can include. - """ - - values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class Property(proto.Message): - r"""Defines properties that can be part of the entity type. - - Attributes: - name (str): - The name of the property. Follows the same - guidelines as the EntityType name. - value_type (str): - A reference to the value type of the property. This type is - subject to the same conventions as the ``Entity.base_types`` - field. - occurrence_type (google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.Property.OccurrenceType): - Occurrence type limits the number of - instances an entity type appears in the - document. - """ - class OccurrenceType(proto.Enum): - r"""Types of occurrences of the entity type in the document. - Note: this represents the number of instances of an entity - types, not number of mentions of a given entity instance. - - Values: - OCCURRENCE_TYPE_UNSPECIFIED (0): - Unspecified occurrence type. - OPTIONAL_ONCE (1): - There will be zero or one instance of this - entity type. - OPTIONAL_MULTIPLE (2): - The entity type will appear zero or multiple - times. - REQUIRED_ONCE (3): - The entity type will only appear exactly - once. - REQUIRED_MULTIPLE (4): - The entity type will appear once or more - times. - """ - OCCURRENCE_TYPE_UNSPECIFIED = 0 - OPTIONAL_ONCE = 1 - OPTIONAL_MULTIPLE = 2 - REQUIRED_ONCE = 3 - REQUIRED_MULTIPLE = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value_type: str = proto.Field( - proto.STRING, - number=2, - ) - occurrence_type: 'DocumentSchema.EntityType.Property.OccurrenceType' = proto.Field( - proto.ENUM, - number=3, - enum='DocumentSchema.EntityType.Property.OccurrenceType', - ) - - enum_values: 'DocumentSchema.EntityType.EnumValues' = proto.Field( - proto.MESSAGE, - number=14, - oneof='value_source', - message='DocumentSchema.EntityType.EnumValues', - ) - display_name: str = proto.Field( - proto.STRING, - number=13, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - base_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - properties: MutableSequence['DocumentSchema.EntityType.Property'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='DocumentSchema.EntityType.Property', - ) - - class Metadata(proto.Message): - r"""Metadata for global schema behavior. - - Attributes: - document_splitter (bool): - If true, a ``document`` entity type can be applied to - subdocument ( splitting). Otherwise, it can only be applied - to the entire document (classification). - document_allow_multiple_labels (bool): - If true, on a given page, there can be multiple ``document`` - annotations covering it. - prefixed_naming_on_properties (bool): - If set, all the nested entities must be - prefixed with the parents. - skip_naming_validation (bool): - If set, we will skip the naming format validation in the - schema. So the string values in - ``DocumentSchema.EntityType.name`` and - ``DocumentSchema.EntityType.Property.name`` will not be - checked. - """ - - document_splitter: bool = proto.Field( - proto.BOOL, - number=1, - ) - document_allow_multiple_labels: bool = proto.Field( - proto.BOOL, - number=2, - ) - prefixed_naming_on_properties: bool = proto.Field( - proto.BOOL, - number=6, - ) - skip_naming_validation: bool = proto.Field( - proto.BOOL, - number=7, - ) - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - entity_types: MutableSequence[EntityType] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=EntityType, - ) - metadata: Metadata = proto.Field( - proto.MESSAGE, - number=4, - message=Metadata, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py deleted file mode 100644 index 6bb882c9..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py +++ /dev/null @@ -1,342 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'EvaluationReference', - 'Evaluation', - }, -) - - -class EvaluationReference(proto.Message): - r"""Gives a short summary of an evaluation, and links to the - evaluation itself. - - Attributes: - operation (str): - The resource name of the Long Running - Operation for the evaluation. - evaluation (str): - The resource name of the evaluation. - aggregate_metrics (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): - An aggregate of the statistics for the - evaluation with fuzzy matching on. - aggregate_metrics_exact (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): - An aggregate of the statistics for the - evaluation with fuzzy matching off. - """ - - operation: str = proto.Field( - proto.STRING, - number=1, - ) - evaluation: str = proto.Field( - proto.STRING, - number=2, - ) - aggregate_metrics: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=4, - message='Evaluation.Metrics', - ) - aggregate_metrics_exact: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=5, - message='Evaluation.Metrics', - ) - - -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. - - Values: - METRICS_TYPE_UNSPECIFIED (0): - The metrics type is unspecified. By default, - metrics without a particular specification are - for leaf entity types (i.e., top-level entity - types without child types, or child types which - are not parent types themselves). - AGGREGATE (1): - Indicates whether metrics for this particular - label type represent an aggregate of metrics for - other types instead of being based on actual - TP/FP/FN values for the label type. Metrics for - parent (i.e., non-leaf) entity types are an - aggregate of metrics for their children. - """ - 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/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py deleted file mode 100644 index 7f329da0..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- 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 - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'Vertex', - 'NormalizedVertex', - 'BoundingPoly', - }, -) - - -class Vertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the vertex coordinates are in the same scale as the - original image. - - Attributes: - x (int): - X coordinate. - y (int): - Y coordinate (starts from the top of the - image). - """ - - x: int = proto.Field( - proto.INT32, - number=1, - ) - y: int = proto.Field( - proto.INT32, - number=2, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate (starts from the top of the - image). - """ - - x: float = proto.Field( - proto.FLOAT, - number=1, - ) - y: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class BoundingPoly(proto.Message): - r"""A bounding polygon for the detected image annotation. - - Attributes: - vertices (MutableSequence[google.cloud.documentai_v1beta3.types.Vertex]): - The bounding polygon vertices. - normalized_vertices (MutableSequence[google.cloud.documentai_v1beta3.types.NormalizedVertex]): - The bounding polygon normalized vertices. - """ - - vertices: MutableSequence['Vertex'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py deleted file mode 100644 index 69e402a1..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'CommonOperationMetadata', - }, -) - - -class CommonOperationMetadata(proto.Message): - r"""The common metadata for long running operations. - - Attributes: - state (google.cloud.documentai_v1beta3.types.CommonOperationMetadata.State): - The state of the operation. - state_message (str): - A message providing more details about the - current state of processing. - resource (str): - A related resource to this operation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - """ - class State(proto.Enum): - r"""State of the longrunning operation. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - RUNNING (1): - Operation is still running. - CANCELLING (2): - Operation is being cancelled. - SUCCEEDED (3): - Operation succeeded. - FAILED (4): - Operation failed. - CANCELLED (5): - Operation is cancelled. - """ - STATE_UNSPECIFIED = 0 - RUNNING = 1 - CANCELLING = 2 - SUCCEEDED = 3 - FAILED = 4 - CANCELLED = 5 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - resource: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py deleted file mode 100644 index 153bc8b5..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py +++ /dev/null @@ -1,285 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.cloud.documentai_v1beta3.types import document_schema as gcd_document_schema -from google.cloud.documentai_v1beta3.types import evaluation -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'ProcessorVersion', - 'Processor', - }, -) - - -class ProcessorVersion(proto.Message): - r"""A processor version is an implementation of a processor. Each - processor can have multiple versions, pre-trained by Google - internally or up-trained by the customer. At a time, a processor - can only have one default version version. So the processor's - behavior (when processing documents) is defined by a default - version - - Attributes: - name (str): - The resource name of the processor version. Format: - ``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): - The time the processor version was created. - latest_evaluation (google.cloud.documentai_v1beta3.types.EvaluationReference): - The most recently invoked evaluation for the - processor version. - 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. - google_managed (bool): - Denotes that this ProcessorVersion is managed - by google. - deprecation_info (google.cloud.documentai_v1beta3.types.ProcessorVersion.DeprecationInfo): - If set, information about the eventual - deprecation of this version. - """ - class State(proto.Enum): - r"""The possible states of the processor version. - - Values: - STATE_UNSPECIFIED (0): - The processor version is in an unspecified - state. - DEPLOYED (1): - The processor version is deployed and can be - used for processing. - DEPLOYING (2): - The processor version is being deployed. - UNDEPLOYED (3): - The processor version is not deployed and - cannot be used for processing. - UNDEPLOYING (4): - The processor version is being undeployed. - CREATING (5): - The processor version is being created. - DELETING (6): - The processor version is being deleted. - FAILED (7): - The processor version failed and is in an - indeterminate state. - """ - STATE_UNSPECIFIED = 0 - DEPLOYED = 1 - DEPLOYING = 2 - UNDEPLOYED = 3 - UNDEPLOYING = 4 - CREATING = 5 - DELETING = 6 - FAILED = 7 - - class DeprecationInfo(proto.Message): - r"""Information about the upcoming deprecation of this processor - version. - - Attributes: - deprecation_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which this processor version will - be deprecated. - replacement_processor_version (str): - If set, the processor version that will be - used as a replacement. - """ - - deprecation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - replacement_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - 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, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - latest_evaluation: evaluation.EvaluationReference = proto.Field( - proto.MESSAGE, - number=8, - message=evaluation.EvaluationReference, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=9, - ) - kms_key_version_name: str = proto.Field( - proto.STRING, - number=10, - ) - google_managed: bool = proto.Field( - proto.BOOL, - number=11, - ) - deprecation_info: DeprecationInfo = proto.Field( - proto.MESSAGE, - number=13, - message=DeprecationInfo, - ) - - -class Processor(proto.Message): - r"""The first-class citizen for Document AI. Each processor - defines how to extract structural information from a document. - - Attributes: - name (str): - Output only. Immutable. The resource name of the processor. - 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 - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes]. - display_name (str): - The display name of the processor. - state (google.cloud.documentai_v1beta3.types.Processor.State): - Output only. The state of the processor. - default_processor_version (str): - The default processor version. - process_endpoint (str): - Output only. Immutable. The http endpoint - that can be called to invoke processing. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the processor was created. - kms_key_name (str): - The KMS key used for encryption/decryption in - CMEK scenarios. See - https://cloud.google.com/security-key-management. - """ - class State(proto.Enum): - r"""The possible states of the processor. - - Values: - STATE_UNSPECIFIED (0): - The processor is in an unspecified state. - ENABLED (1): - The processor is enabled, i.e., has an - enabled version which can currently serve - processing requests and all the feature - dependencies have been successfully initialized. - DISABLED (2): - The processor is disabled. - ENABLING (3): - The processor is being enabled, will become ``ENABLED`` if - successful. - DISABLING (4): - The processor is being disabled, will become ``DISABLED`` if - successful. - CREATING (5): - The processor is being created, will become either - ``ENABLED`` (for successful creation) or ``FAILED`` (for - failed ones). Once a processor is in this state, it can then - be used for document processing, but the feature - dependencies of the processor might not be fully created - yet. - FAILED (6): - The processor failed during creation or - initialization of feature dependencies. The user - should delete the processor and recreate one as - all the functionalities of the processor are - disabled. - DELETING (7): - The processor is being deleted, will be - removed if successful. - """ - STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - ENABLING = 3 - DISABLING = 4 - CREATING = 5 - FAILED = 6 - DELETING = 7 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=9, - ) - process_endpoint: str = proto.Field( - proto.STRING, - number=6, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py deleted file mode 100644 index 79381f6b..00000000 --- a/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py +++ /dev/null @@ -1,106 +0,0 @@ -# -*- 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 - -import proto # type: ignore - -from google.api import launch_stage_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'ProcessorType', - }, -) - - -class ProcessorType(proto.Message): - r"""A processor type is responsible for performing a certain - document understanding task on a certain type of document. - - Attributes: - name (str): - The resource name of the processor type. Format: - ``projects/{project}/processorTypes/{processor_type}`` - type_ (str): - The processor type, e.g., ``OCR_PROCESSOR``, - ``INVOICE_PROCESSOR``, etc. - category (str): - The processor category, used by UI to group - processor types. - available_locations (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType.LocationInfo]): - The locations in which this processor is - available. - allow_creation (bool): - Whether the processor type allows creation. - If true, users can create a processor of this - processor type. Otherwise, users need to request - access. - launch_stage (google.api.launch_stage_pb2.LaunchStage): - Launch stage of the processor type - sample_document_uris (MutableSequence[str]): - A set of Cloud Storage URIs of sample - documents for this processor. - """ - - class LocationInfo(proto.Message): - r"""The location information about where the processor is - available. - - Attributes: - location_id (str): - The location id, currently must be one of [us, eu]. - """ - - location_id: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - category: str = proto.Field( - proto.STRING, - number=3, - ) - available_locations: MutableSequence[LocationInfo] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=LocationInfo, - ) - allow_creation: bool = proto.Field( - proto.BOOL, - number=6, - ) - launch_stage: launch_stage_pb2.LaunchStage = proto.Field( - proto.ENUM, - number=8, - enum=launch_stage_pb2.LaunchStage, - ) - sample_document_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta3/mypy.ini b/owl-bot-staging/v1beta3/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/owl-bot-staging/v1beta3/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1beta3/noxfile.py b/owl-bot-staging/v1beta3/noxfile.py deleted file mode 100644 index ef7ddc7a..00000000 --- a/owl-bot-staging/v1beta3/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- 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. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/documentai_v1beta3/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py deleted file mode 100644 index 9a52ef4a..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 BatchProcessDocuments -# 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_BatchProcessDocuments_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_batch_process_documents(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py deleted file mode 100644 index 25f76623..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 BatchProcessDocuments -# 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_BatchProcessDocuments_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_batch_process_documents(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py deleted file mode 100644 index 8487077f..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 CreateProcessor -# 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_CreateProcessor_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_create_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py deleted file mode 100644 index 2705de55..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 CreateProcessor -# 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_CreateProcessor_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_create_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py deleted file mode 100644 index 54141136..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessor -# 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_DeleteProcessor_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_delete_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py deleted file mode 100644 index 38e0353b..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessor -# 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_DeleteProcessor_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_delete_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py deleted file mode 100644 index 16913bec..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessorVersion -# 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_DeleteProcessorVersion_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_delete_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py deleted file mode 100644 index d291a9ae..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteProcessorVersion -# 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_DeleteProcessorVersion_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_delete_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py deleted file mode 100644 index e5b67ec9..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeployProcessorVersion -# 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_DeployProcessorVersion_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_deploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py deleted file mode 100644 index 3ad835fe..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeployProcessorVersion -# 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_DeployProcessorVersion_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_deploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py deleted file mode 100644 index 2bc67064..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DisableProcessor -# 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_DisableProcessor_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_disable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py deleted file mode 100644 index 4f3d70ab..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DisableProcessor -# 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_DisableProcessor_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_disable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py deleted file mode 100644 index 8d4dfd9e..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 EnableProcessor -# 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_EnableProcessor_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_enable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py deleted file mode 100644 index 98b1561f..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 EnableProcessor -# 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_EnableProcessor_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_enable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py deleted file mode 100644 index 8290b418..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py deleted file mode 100644 index fb730993..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py deleted file mode 100644 index 9c0ab5dd..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 FetchProcessorTypes -# 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_FetchProcessorTypes_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_fetch_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.fetch_processor_types(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py deleted file mode 100644 index df7a7069..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 FetchProcessorTypes -# 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_FetchProcessorTypes_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_fetch_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = client.fetch_processor_types(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py deleted file mode 100644 index c2306172..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py deleted file mode 100644 index d126b6bd..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py deleted file mode 100644 index cc90dd2e..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessor -# 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_GetProcessor_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_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py deleted file mode 100644 index ebdf0676..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessor -# 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_GetProcessor_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_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py deleted file mode 100644 index 6f276a69..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorType -# 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_GetProcessorType_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_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py deleted file mode 100644 index 1db0b26c..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorType -# 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_GetProcessorType_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_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py deleted file mode 100644 index 27a73ebb..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorVersion -# 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_GetProcessorVersion_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_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_version(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py deleted file mode 100644 index d4a19a6d..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetProcessorVersion -# 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_GetProcessorVersion_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_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_version(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py deleted file mode 100644 index be38a005..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py deleted file mode 100644 index 3849d890..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py deleted file mode 100644 index 9e42bdf3..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorTypes -# 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_ListProcessorTypes_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_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py deleted file mode 100644 index ff735a06..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorTypes -# 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_ListProcessorTypes_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_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py deleted file mode 100644 index 6179291d..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorVersions -# 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_ListProcessorVersions_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_processor_versions(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py deleted file mode 100644 index 981de716..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessorVersions -# 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_ListProcessorVersions_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_processor_versions(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py deleted file mode 100644 index c9bb0a54..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessors -# 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_ListProcessors_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_processors(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py deleted file mode 100644 index 2b853df9..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListProcessors -# 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_ListProcessors_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_processors(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py deleted file mode 100644 index c9f2346e..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 ProcessDocument -# 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_ProcessDocument_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_process_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py deleted file mode 100644 index cfae6a5e..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 ProcessDocument -# 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_ProcessDocument_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_process_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py deleted file mode 100644 index ddafdd90..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- 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 ReviewDocument -# 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_ReviewDocument_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_review_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py deleted file mode 100644 index 66a9bec3..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- 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 ReviewDocument -# 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_ReviewDocument_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_review_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py deleted file mode 100644 index bf49fea1..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- 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 SetDefaultProcessorVersion -# 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_SetDefaultProcessorVersion_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_set_default_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py deleted file mode 100644 index 95b38d3b..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- 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 SetDefaultProcessorVersion -# 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_SetDefaultProcessorVersion_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_set_default_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py deleted file mode 100644 index e1c21207..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py deleted file mode 100644 index 3d9fa4ea..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py deleted file mode 100644 index fbbc23db..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 UndeployProcessorVersion -# 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_UndeployProcessorVersion_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_undeploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_async] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py b/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py deleted file mode 100644 index eb761cb3..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 UndeployProcessorVersion -# 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_UndeployProcessorVersion_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_undeploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_sync] diff --git a/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json b/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json deleted file mode 100644 index f02752f1..00000000 --- a/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json +++ /dev/null @@ -1,3549 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.documentai.v1beta3", - "version": "v1beta3" - } - ], - "language": "PYTHON", - "name": "google-cloud-documentai", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.BatchProcessRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_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_batch_process_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.BatchProcessRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_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_batch_process_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1beta3.types.Processor" - }, - { - "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.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_create_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_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_create_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1beta3.types.Processor" - }, - { - "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.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_create_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_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_create_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_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_delete_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_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_delete_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_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_delete_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_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_delete_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_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_deploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_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_deploy_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DisableProcessorRequest" - }, - { - "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": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_disable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_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_disable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DisableProcessorRequest" - }, - { - "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": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_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_disable_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.EnableProcessorRequest" - }, - { - "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": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_enable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_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_enable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.EnableProcessorRequest" - }, - { - "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": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_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_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": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.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_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_type", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest" - }, - { - "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.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_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_processor_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor_type", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest" - }, - { - "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.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_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_processor_type_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_GetProcessorVersion_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_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.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_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_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_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" - }, - { - "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.Processor", - "shortName": "get_processor" - }, - "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_GetProcessor_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_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" - }, - { - "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.Processor", - "shortName": "get_processor" - }, - "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_GetProcessor_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_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" - }, - { - "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.services.document_processor_service.pagers.ListEvaluationsAsyncPager", - "shortName": "list_evaluations" - }, - "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_ListEvaluations_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" - }, - { - "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.services.document_processor_service.pagers.ListEvaluationsPager", - "shortName": "list_evaluations" - }, - "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_ListEvaluations_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest" - }, - { - "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.services.document_processor_service.pagers.ListProcessorTypesAsyncPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest" - }, - { - "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.services.document_processor_service.pagers.ListProcessorTypesPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest" - }, - { - "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.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest" - }, - { - "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.services.document_processor_service.pagers.ListProcessorVersionsPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorsRequest" - }, - { - "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.services.document_processor_service.pagers.ListProcessorsAsyncPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1beta3_generated_document_processor_service_list_processors_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processors_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorsRequest" - }, - { - "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.services.document_processor_service.pagers.ListProcessorsPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1beta3_generated_document_processor_service_list_processors_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processors_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ProcessRequest" - }, - { - "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.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta3_generated_document_processor_service_process_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_process_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ProcessRequest" - }, - { - "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.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta3_generated_document_processor_service_process_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_process_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "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": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1beta3_generated_document_processor_service_review_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_review_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "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": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1beta3_generated_document_processor_service_review_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_review_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest" - }, - { - "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": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest" - }, - { - "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": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "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": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_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_undeploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_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_undeploy_processor_version_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py b/owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py deleted file mode 100644 index 75ec155f..00000000 --- a/owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py +++ /dev/null @@ -1,197 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class documentaiCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_process_documents': ('name', 'input_configs', 'output_config', 'input_documents', 'document_output_config', 'skip_human_review', 'process_options', ), - 'create_processor': ('parent', 'processor', ), - 'delete_processor': ('name', ), - 'delete_processor_version': ('name', ), - '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_type': ('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', 'process_options', ), - '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', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=documentaiCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the documentai client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta3/setup.py b/owl-bot-staging/v1beta3/setup.py deleted file mode 100644 index 3b12ce4b..00000000 --- a/owl-bot-staging/v1beta3/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- 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. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-documentai' - - -description = "Google Cloud Documentai API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-documentai" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.10.txt b/owl-bot-staging/v1beta3/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta3/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.11.txt b/owl-bot-staging/v1beta3/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta3/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.12.txt b/owl-bot-staging/v1beta3/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta3/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.7.txt b/owl-bot-staging/v1beta3/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfe..00000000 --- a/owl-bot-staging/v1beta3/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.8.txt b/owl-bot-staging/v1beta3/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta3/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta3/testing/constraints-3.9.txt b/owl-bot-staging/v1beta3/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/owl-bot-staging/v1beta3/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1beta3/tests/__init__.py b/owl-bot-staging/v1beta3/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta3/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta3/tests/unit/__init__.py b/owl-bot-staging/v1beta3/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta3/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta3/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py b/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py b/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py deleted file mode 100644 index d50c24f1..00000000 --- a/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py +++ /dev/null @@ -1,13258 +0,0 @@ -# -*- 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. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.documentai_v1beta3.services.document_processor_service import DocumentProcessorServiceAsyncClient -from google.cloud.documentai_v1beta3.services.document_processor_service import DocumentProcessorServiceClient -from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.services.document_processor_service import transports -from google.cloud.documentai_v1beta3.types import barcode -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_io -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import geometry -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 -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import color_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import money_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(None) is None - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentProcessorServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -def test_document_processor_service_client_get_transport_class(): - transport = DocumentProcessorServiceClient.get_transport_class() - available_transports = [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentProcessorServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentProcessorServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) -def test_document_processor_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(DocumentProcessorServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "true"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "false"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_document_processor_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentProcessorServiceClient, DocumentProcessorServiceAsyncClient -]) -@mock.patch.object(DocumentProcessorServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentProcessorServiceAsyncClient)) -def test_document_processor_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", None), -]) -def test_document_processor_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_document_processor_service_client_client_options_from_dict(): - with mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentProcessorServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_processor_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ProcessRequest, - dict, -]) -def test_process_document(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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ProcessResponse( - human_review_operation='human_review_operation_value', - ) - response = client.process_document(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.ProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - assert response.human_review_operation == 'human_review_operation_value' - - -def test_process_document_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.process_document), - '__call__') as call: - client.process_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ProcessRequest() - -@pytest.mark.asyncio -async def test_process_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ProcessRequest): - 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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse( - human_review_operation='human_review_operation_value', - )) - response = await client.process_document(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.ProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - assert response.human_review_operation == 'human_review_operation_value' - - -@pytest.mark.asyncio -async def test_process_document_async_from_dict(): - await test_process_document_async(request_type=dict) - - -def test_process_document_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.ProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.process_document), - '__call__') as call: - call.return_value = document_processor_service.ProcessResponse() - client.process_document(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_process_document_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.ProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.process_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) - await client.process_document(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_process_document_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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ProcessResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.process_document( - 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_process_document_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.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_process_document_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.process_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ProcessResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ProcessResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.process_document( - 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_process_document_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.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.BatchProcessRequest, - dict, -]) -def test_batch_process_documents(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.batch_process_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_process_documents(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.BatchProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_process_documents_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.batch_process_documents), - '__call__') as call: - client.batch_process_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.BatchProcessRequest() - -@pytest.mark.asyncio -async def test_batch_process_documents_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.BatchProcessRequest): - 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.batch_process_documents), - '__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.batch_process_documents(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.BatchProcessRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_process_documents_async_from_dict(): - await test_batch_process_documents_async(request_type=dict) - - -def test_batch_process_documents_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.BatchProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_process_documents(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_batch_process_documents_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.BatchProcessRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_process_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_process_documents(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_batch_process_documents_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.batch_process_documents), - '__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.batch_process_documents( - 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_batch_process_documents_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.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_batch_process_documents_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.batch_process_documents), - '__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.batch_process_documents( - 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_batch_process_documents_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.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.FetchProcessorTypesRequest, - dict, -]) -def test_fetch_processor_types(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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.FetchProcessorTypesResponse( - ) - response = client.fetch_processor_types(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.FetchProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -def test_fetch_processor_types_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.fetch_processor_types), - '__call__') as call: - client.fetch_processor_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.FetchProcessorTypesRequest() - -@pytest.mark.asyncio -async def test_fetch_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.FetchProcessorTypesRequest): - 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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse( - )) - response = await client.fetch_processor_types(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.FetchProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -@pytest.mark.asyncio -async def test_fetch_processor_types_async_from_dict(): - await test_fetch_processor_types_async(request_type=dict) - - -def test_fetch_processor_types_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.FetchProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_processor_types), - '__call__') as call: - call.return_value = document_processor_service.FetchProcessorTypesResponse() - client.fetch_processor_types(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_fetch_processor_types_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.FetchProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_processor_types), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) - await client.fetch_processor_types(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_fetch_processor_types_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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.FetchProcessorTypesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.fetch_processor_types( - 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_fetch_processor_types_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.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_fetch_processor_types_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.fetch_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.FetchProcessorTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.FetchProcessorTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.fetch_processor_types( - 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_fetch_processor_types_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.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorTypesRequest, - dict, -]) -def test_list_processor_types(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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processor_types(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.ListProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_types_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_processor_types), - '__call__') as call: - client.list_processor_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorTypesRequest() - -@pytest.mark.asyncio -async def test_list_processor_types_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorTypesRequest): - 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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processor_types(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.ListProcessorTypesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processor_types_async_from_dict(): - await test_list_processor_types_async(request_type=dict) - - -def test_list_processor_types_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.ListProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_types), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorTypesResponse() - client.list_processor_types(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_processor_types_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.ListProcessorTypesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_types), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) - await client.list_processor_types(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_processor_types_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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorTypesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processor_types( - 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_processor_types_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_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processor_types_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_processor_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processor_types( - 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_processor_types_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_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_list_processor_types_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_processor_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processor_types(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor_type.ProcessorType) - for i in results) -def test_list_processor_types_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_processor_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processor_types(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_processor_types_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_processor_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processor_types(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, processor_type.ProcessorType) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processor_types_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_processor_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_processor_types(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 - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type(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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - response = client.get_processor_type(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.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_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_processor_type), - '__call__') as call: - client.get_processor_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - -@pytest.mark.asyncio -async def test_get_processor_type_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorTypeRequest): - 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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - )) - response = await client.get_processor_type(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.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -@pytest.mark.asyncio -async def test_get_processor_type_async_from_dict(): - await test_get_processor_type_async(request_type=dict) - - -def test_get_processor_type_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.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = processor_type.ProcessorType() - client.get_processor_type(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_processor_type_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.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - await client.get_processor_type(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_processor_type_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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor_type( - 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_processor_type_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_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_type_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_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor_type( - 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_processor_type_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_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors(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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processors(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.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_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_processors), - '__call__') as call: - client.list_processors() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - -@pytest.mark.asyncio -async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorsRequest): - 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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processors(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.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processors_async_from_dict(): - await test_list_processors_async(request_type=dict) - - -def test_list_processors_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.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorsResponse() - client.list_processors(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_processors_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.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - await client.list_processors(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_processors_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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processors( - 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_processors_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_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processors_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_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processors( - 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_processors_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_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_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_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processors(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) -def test_list_processors_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_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processors(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_processors_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_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processors(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, processor.Processor) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processors_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_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_processors(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 - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor(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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.get_processor(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.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_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_processor), - '__call__') as call: - client.get_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - -@pytest.mark.asyncio -async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorRequest): - 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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.get_processor(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.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_get_processor_async_from_dict(): - await test_get_processor_async(request_type=dict) - - -def test_get_processor_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.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = processor.Processor() - client.get_processor(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_processor_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.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - await client.get_processor(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_processor_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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor( - 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_processor_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_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_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_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor( - 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_processor_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_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -@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", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_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.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - ) - response = client.get_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.GetProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - - -def test_get_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.get_processor_version), - '__call__') as call: - client.get_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_get_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorVersionRequest): - 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_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - )) - response = await client.get_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.GetProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - - -@pytest.mark.asyncio -async def test_get_processor_version_async_from_dict(): - await test_get_processor_version_async(request_type=dict) - - -def test_get_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.GetProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_version), - '__call__') as call: - call.return_value = processor.ProcessorVersion() - client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_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.GetProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) - await client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_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.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor_version( - 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_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.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_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.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.ProcessorVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor_version( - 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_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.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorVersionsRequest, - dict, -]) -def test_list_processor_versions(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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processor_versions(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.ListProcessorVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_versions_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_processor_versions), - '__call__') as call: - client.list_processor_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorVersionsRequest() - -@pytest.mark.asyncio -async def test_list_processor_versions_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorVersionsRequest): - 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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processor_versions(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.ListProcessorVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processor_versions_async_from_dict(): - await test_list_processor_versions_async(request_type=dict) - - -def test_list_processor_versions_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.ListProcessorVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_versions), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorVersionsResponse() - client.list_processor_versions(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_processor_versions_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.ListProcessorVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processor_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) - await client.list_processor_versions(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_processor_versions_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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processor_versions( - 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_processor_versions_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_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processor_versions_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_processor_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processor_versions( - 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_processor_versions_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_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - - -def test_list_processor_versions_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_processor_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processor_versions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.ProcessorVersion) - for i in results) -def test_list_processor_versions_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_processor_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processor_versions(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_processor_versions_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_processor_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processor_versions(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, processor.ProcessorVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processor_versions_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_processor_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_processor_versions(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 - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_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.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_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.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_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.delete_processor_version), - '__call__') as call: - client.delete_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_delete_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorVersionRequest): - 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.delete_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.delete_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.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_version_async_from_dict(): - await test_delete_processor_version_async(request_type=dict) - - -def test_delete_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.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_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.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_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.delete_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.delete_processor_version( - 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_delete_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.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_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.delete_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.delete_processor_version( - 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_delete_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.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_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.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.deploy_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.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_deploy_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.deploy_processor_version), - '__call__') as call: - client.deploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_deploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeployProcessorVersionRequest): - 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.deploy_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.deploy_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.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_deploy_processor_version_async_from_dict(): - await test_deploy_processor_version_async(request_type=dict) - - -def test_deploy_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.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.deploy_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_deploy_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.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.deploy_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_deploy_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.deploy_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.deploy_processor_version( - 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_deploy_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.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_deploy_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.deploy_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.deploy_processor_version( - 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_deploy_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.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_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.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undeploy_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.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undeploy_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.undeploy_processor_version), - '__call__') as call: - client.undeploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.UndeployProcessorVersionRequest): - 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.undeploy_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.undeploy_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.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async_from_dict(): - await test_undeploy_processor_version_async(request_type=dict) - - -def test_undeploy_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.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undeploy_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_undeploy_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.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undeploy_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_undeploy_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.undeploy_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.undeploy_processor_version( - 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_undeploy_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.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_undeploy_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.undeploy_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.undeploy_processor_version( - 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_undeploy_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.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor(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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.create_processor(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.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_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.create_processor), - '__call__') as call: - client.create_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - -@pytest.mark.asyncio -async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.CreateProcessorRequest): - 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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.create_processor(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.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_create_processor_async_from_dict(): - await test_create_processor_async(request_type=dict) - - -def test_create_processor_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.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = gcd_processor.Processor() - client.create_processor(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_create_processor_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.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - await client.create_processor(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_create_processor_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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(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 - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - - -def test_create_processor_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.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_processor_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.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(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 - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_processor_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.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor(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.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_processor(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.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_processor_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.delete_processor), - '__call__') as call: - client.delete_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - -@pytest.mark.asyncio -async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorRequest): - 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.delete_processor), - '__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.delete_processor(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.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_async_from_dict(): - await test_delete_processor_async(request_type=dict) - - -def test_delete_processor_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.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_processor(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_delete_processor_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.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_processor(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_delete_processor_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.delete_processor), - '__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.delete_processor( - 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_delete_processor_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.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_processor_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.delete_processor), - '__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.delete_processor( - 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_delete_processor_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.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor(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.enable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.enable_processor(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.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_enable_processor_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.enable_processor), - '__call__') as call: - client.enable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - -@pytest.mark.asyncio -async def test_enable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EnableProcessorRequest): - 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.enable_processor), - '__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.enable_processor(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.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_enable_processor_async_from_dict(): - await test_enable_processor_async(request_type=dict) - - -def test_enable_processor_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.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.enable_processor(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_enable_processor_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.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.enable_processor(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'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor(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.disable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.disable_processor(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.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_disable_processor_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.disable_processor), - '__call__') as call: - client.disable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - -@pytest.mark.asyncio -async def test_disable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DisableProcessorRequest): - 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.disable_processor), - '__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.disable_processor(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.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_disable_processor_async_from_dict(): - await test_disable_processor_async(request_type=dict) - - -def test_disable_processor_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.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.disable_processor(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_disable_processor_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.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.disable_processor(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'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_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.set_default_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_default_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.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_default_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.set_default_processor_version), - '__call__') as call: - client.set_default_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_set_default_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - 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.set_default_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.set_default_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.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_default_processor_version_async_from_dict(): - await test_set_default_processor_version_async(request_type=dict) - - -def test_set_default_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.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_default_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=processor_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_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.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_default_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=processor_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document(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.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.review_document(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.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_review_document_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.review_document), - '__call__') as call: - client.review_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - -@pytest.mark.asyncio -async def test_review_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ReviewDocumentRequest): - 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.review_document), - '__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.review_document(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.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_review_document_async_from_dict(): - await test_review_document_async(request_type=dict) - - -def test_review_document_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.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.review_document(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', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_review_document_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.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.review_document(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', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -def test_review_document_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.review_document), - '__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.review_document( - human_review_config='human_review_config_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].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - - -def test_review_document_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.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - -@pytest.mark.asyncio -async def test_review_document_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.review_document), - '__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.review_document( - human_review_config='human_review_config_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].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_review_document_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.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -@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, - ) - - # 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 = 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', - ) - - # 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 - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ProcessRequest, - dict, -]) -def test_process_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse( - human_review_operation='human_review_operation_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.process_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - assert response.human_review_operation == 'human_review_operation_value' - - -def test_process_document_rest_required_fields(request_type=document_processor_service.ProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.process_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_process_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.process_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_process_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_process_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_process_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ProcessRequest.pb(document_processor_service.ProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ProcessResponse.to_json(document_processor_service.ProcessResponse()) - - request = document_processor_service.ProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ProcessResponse() - - client.process_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_process_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.process_document(request) - - -def test_process_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.process_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}:process" % client.transport._host, args[1]) - - -def test_process_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - - -def test_process_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.BatchProcessRequest, - dict, -]) -def test_batch_process_documents_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_process_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_process_documents_rest_required_fields(request_type=document_processor_service.BatchProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_process_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_process_documents_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_process_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_process_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_batch_process_documents") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_batch_process_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.BatchProcessRequest.pb(document_processor_service.BatchProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.BatchProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_process_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_process_documents_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.BatchProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_process_documents(request) - - -def test_batch_process_documents_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_process_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}:batchProcess" % client.transport._host, args[1]) - - -def test_batch_process_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - - -def test_batch_process_documents_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.FetchProcessorTypesRequest, - dict, -]) -def test_fetch_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.fetch_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -def test_fetch_processor_types_rest_required_fields(request_type=document_processor_service.FetchProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.fetch_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.FetchProcessorTypesRequest.pb(document_processor_service.FetchProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.FetchProcessorTypesResponse.to_json(document_processor_service.FetchProcessorTypesResponse()) - - request = document_processor_service.FetchProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.FetchProcessorTypesResponse() - - client.fetch_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.FetchProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_processor_types(request) - - -def test_fetch_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.fetch_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}:fetchProcessorTypes" % client.transport._host, args[1]) - - -def test_fetch_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_fetch_processor_types_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorTypesRequest, - dict, -]) -def test_list_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_types_rest_required_fields(request_type=document_processor_service.ListProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorTypesRequest.pb(document_processor_service.ListProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorTypesResponse.to_json(document_processor_service.ListProcessorTypesResponse()) - - request = document_processor_service.ListProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorTypesResponse() - - client.list_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_types(request) - - -def test_list_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processorTypes" % client.transport._host, args[1]) - - -def test_list_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_list_processor_types_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processor_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor_type.ProcessorType) - for i in results) - - pages = list(client.list_processor_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_type(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_rest_required_fields(request_type=document_processor_service.GetProcessorTypeRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_type_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_type_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorTypeRequest.pb(document_processor_service.GetProcessorTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor_type.ProcessorType.to_json(processor_type.ProcessorType()) - - request = document_processor_service.GetProcessorTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor_type.ProcessorType() - - client.get_processor_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_type_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorTypeRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_type(request) - - -def test_get_processor_type_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processorTypes/*}" % client.transport._host, args[1]) - - -def test_get_processor_type_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -def test_get_processor_type_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processors(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_rest_required_fields(request_type=document_processor_service.ListProcessorsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processors(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processors_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processors._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processors_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processors") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorsRequest.pb(document_processor_service.ListProcessorsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorsResponse.to_json(document_processor_service.ListProcessorsResponse()) - - request = document_processor_service.ListProcessorsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorsResponse() - - client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processors(request) - - -def test_list_processors_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processors(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_list_processors_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processors(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) - - pages = list(client.list_processors(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_rest_required_fields(request_type=document_processor_service.GetProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorRequest.pb(document_processor_service.GetProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.Processor.to_json(processor.Processor()) - - request = document_processor_service.GetProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.Processor() - - client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor(request) - - -def test_get_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_get_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -def test_get_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.TrainProcessorVersionRequest, - dict, -]) -def test_train_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.train_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_train_processor_version_rest_required_fields(request_type=document_processor_service.TrainProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.train_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_train_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.train_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_train_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_train_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_train_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.TrainProcessorVersionRequest.pb(document_processor_service.TrainProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.TrainProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.train_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_train_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.TrainProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.train_processor_version(request) - - -def test_train_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.train_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:train" % client.transport._host, args[1]) - - -def test_train_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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'), - ) - - -def test_train_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - - -def test_get_processor_version_rest_required_fields(request_type=document_processor_service.GetProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorVersionRequest.pb(document_processor_service.GetProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.ProcessorVersion.to_json(processor.ProcessorVersion()) - - request = document_processor_service.GetProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.ProcessorVersion() - - client.get_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_version(request) - - -def test_get_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_get_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - - -def test_get_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorVersionsRequest, - dict, -]) -def test_list_processor_versions_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_versions_rest_required_fields(request_type=document_processor_service.ListProcessorVersionsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_versions_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_versions_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_versions") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorVersionsRequest.pb(document_processor_service.ListProcessorVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorVersionsResponse.to_json(document_processor_service.ListProcessorVersionsResponse()) - - request = document_processor_service.ListProcessorVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorVersionsResponse() - - client.list_processor_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_versions_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorVersionsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_versions(request) - - -def test_list_processor_versions_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions" % client.transport._host, args[1]) - - -def test_list_processor_versions_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - - -def test_list_processor_versions_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorVersionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - pager = client.list_processor_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.ProcessorVersion) - for i in results) - - pages = list(client.list_processor_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_version_rest_required_fields(request_type=document_processor_service.DeleteProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorVersionRequest.pb(document_processor_service.DeleteProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor_version(request) - - -def test_delete_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_delete_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -def test_delete_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.deploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_deploy_processor_version_rest_required_fields(request_type=document_processor_service.DeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.deploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_deploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_deploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_deploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_deploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeployProcessorVersionRequest.pb(document_processor_service.DeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.deploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_deploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.deploy_processor_version(request) - - -def test_deploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.deploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" % client.transport._host, args[1]) - - -def test_deploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_deploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.undeploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_undeploy_processor_version_rest_required_fields(request_type=document_processor_service.UndeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.undeploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undeploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undeploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_undeploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_undeploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.UndeployProcessorVersionRequest.pb(document_processor_service.UndeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.UndeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undeploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undeploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.UndeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.undeploy_processor_version(request) - - -def test_undeploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.undeploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" % client.transport._host, args[1]) - - -def test_undeploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_undeploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_rest_required_fields(request_type=document_processor_service.CreateProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processor", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_create_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.CreateProcessorRequest.pb(document_processor_service.CreateProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_processor.Processor.to_json(gcd_processor.Processor()) - - request = document_processor_service.CreateProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_processor.Processor() - - client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.CreateProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_processor(request) - - -def test_create_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_create_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -def test_create_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_rest_required_fields(request_type=document_processor_service.DeleteProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorRequest.pb(document_processor_service.DeleteProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor(request) - - -def test_delete_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_delete_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -def test_delete_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.enable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_enable_processor_rest_required_fields(request_type=document_processor_service.EnableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.enable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_enable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.enable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EnableProcessorRequest.pb(document_processor_service.EnableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EnableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.enable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_enable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EnableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.enable_processor(request) - - -def test_enable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.disable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_disable_processor_rest_required_fields(request_type=document_processor_service.DisableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.disable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_disable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.disable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DisableProcessorRequest.pb(document_processor_service.DisableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DisableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.disable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_disable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DisableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.disable_processor(request) - - -def test_disable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_default_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_default_processor_version_rest_required_fields(request_type=document_processor_service.SetDefaultProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor"] = "" - request_init["default_processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processor"] = 'processor_value' - jsonified_request["defaultProcessorVersion"] = 'default_processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processor" in jsonified_request - assert jsonified_request["processor"] == 'processor_value' - assert "defaultProcessorVersion" in jsonified_request - assert jsonified_request["defaultProcessorVersion"] == 'default_processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_default_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_default_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_default_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processor", "defaultProcessorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_set_default_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_set_default_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb(document_processor_service.SetDefaultProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.SetDefaultProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_default_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_default_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_default_processor_version(request) - - -def test_set_default_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.review_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_review_document_rest_required_fields(request_type=document_processor_service.ReviewDocumentRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["human_review_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["humanReviewConfig"] = 'human_review_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "humanReviewConfig" in jsonified_request - assert jsonified_request["humanReviewConfig"] == 'human_review_config_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.review_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_review_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.review_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("humanReviewConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_review_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_review_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_review_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ReviewDocumentRequest.pb(document_processor_service.ReviewDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.ReviewDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.review_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_review_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ReviewDocumentRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.review_document(request) - - -def test_review_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - - # get truthy value for each flattened field - mock_args = dict( - human_review_config='human_review_config_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.review_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" % client.transport._host, args[1]) - - -def test_review_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -def test_review_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EvaluateProcessorVersionRequest, - dict, -]) -def test_evaluate_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.evaluate_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_evaluate_processor_version_rest_required_fields(request_type=document_processor_service.EvaluateProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processorVersion"] = 'processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processorVersion" in jsonified_request - assert jsonified_request["processorVersion"] == 'processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.evaluate_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_evaluate_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.evaluate_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_evaluate_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_evaluate_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_evaluate_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EvaluateProcessorVersionRequest.pb(document_processor_service.EvaluateProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EvaluateProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.evaluate_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_evaluate_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EvaluateProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.evaluate_processor_version(request) - - -def test_evaluate_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - processor_version='processor_version_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.evaluate_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion" % client.transport._host, args[1]) - - -def test_evaluate_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_evaluate_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetEvaluationRequest, - dict, -]) -def test_get_evaluation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_evaluation(request) - - # 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_rest_required_fields(request_type=document_processor_service.GetEvaluationRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_evaluation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_evaluation_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_evaluation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_evaluation_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_evaluation") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_evaluation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetEvaluationRequest.pb(document_processor_service.GetEvaluationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = evaluation.Evaluation.to_json(evaluation.Evaluation()) - - request = document_processor_service.GetEvaluationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = evaluation.Evaluation() - - client.get_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_evaluation_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetEvaluationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_evaluation(request) - - -def test_get_evaluation_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_evaluation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}" % client.transport._host, args[1]) - - -def test_get_evaluation_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_get_evaluation_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListEvaluationsRequest, - dict, -]) -def test_list_evaluations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_evaluations(request) - - # 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_rest_required_fields(request_type=document_processor_service.ListEvaluationsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_evaluations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_evaluations_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_evaluations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_evaluations_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_evaluations") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_evaluations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListEvaluationsRequest.pb(document_processor_service.ListEvaluationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListEvaluationsResponse.to_json(document_processor_service.ListEvaluationsResponse()) - - request = document_processor_service.ListEvaluationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListEvaluationsResponse() - - client.list_evaluations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_evaluations_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListEvaluationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_evaluations(request) - - -def test_list_evaluations_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_evaluations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations" % client.transport._host, args[1]) - - -def test_list_evaluations_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_list_evaluations_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - 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(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListEvaluationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - pager = client.list_evaluations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in results) - - pages = list(client.list_evaluations(request=sample_request).pages) - 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( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentProcessorServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentProcessorServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentProcessorServiceGrpcTransport, - ) - -def test_document_processor_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_processor_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'process_document', - 'batch_process_documents', - 'fetch_processor_types', - 'list_processor_types', - 'get_processor_type', - 'list_processors', - 'get_processor', - 'train_processor_version', - 'get_processor_version', - 'list_processor_versions', - 'delete_processor_version', - 'deploy_processor_version', - 'undeploy_processor_version', - 'create_processor', - 'delete_processor', - 'enable_processor', - 'disable_processor', - 'set_default_processor_version', - 'review_document', - 'evaluate_processor_version', - 'get_evaluation', - 'list_evaluations', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_document_processor_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_document_processor_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport() - adc.assert_called_once() - - -def test_document_processor_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentProcessorServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - ], -) -def test_document_processor_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, - ], -) -def test_document_processor_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentProcessorServiceGrpcTransport, grpc_helpers), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_processor_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_document_processor_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DocumentProcessorServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_processor_service_rest_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_no_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_with_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_processor_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentProcessorServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentProcessorServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.process_document._session - session2 = client2.transport.process_document._session - assert session1 != session2 - session1 = client1.transport.batch_process_documents._session - session2 = client2.transport.batch_process_documents._session - assert session1 != session2 - session1 = client1.transport.fetch_processor_types._session - session2 = client2.transport.fetch_processor_types._session - assert session1 != session2 - session1 = client1.transport.list_processor_types._session - session2 = client2.transport.list_processor_types._session - assert session1 != session2 - session1 = client1.transport.get_processor_type._session - session2 = client2.transport.get_processor_type._session - assert session1 != session2 - session1 = client1.transport.list_processors._session - session2 = client2.transport.list_processors._session - assert session1 != session2 - session1 = client1.transport.get_processor._session - session2 = client2.transport.get_processor._session - assert session1 != session2 - session1 = client1.transport.train_processor_version._session - session2 = client2.transport.train_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_processor_version._session - session2 = client2.transport.get_processor_version._session - assert session1 != session2 - session1 = client1.transport.list_processor_versions._session - session2 = client2.transport.list_processor_versions._session - assert session1 != session2 - session1 = client1.transport.delete_processor_version._session - session2 = client2.transport.delete_processor_version._session - assert session1 != session2 - session1 = client1.transport.deploy_processor_version._session - session2 = client2.transport.deploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.undeploy_processor_version._session - session2 = client2.transport.undeploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.create_processor._session - session2 = client2.transport.create_processor._session - assert session1 != session2 - session1 = client1.transport.delete_processor._session - session2 = client2.transport.delete_processor._session - assert session1 != session2 - session1 = client1.transport.enable_processor._session - session2 = client2.transport.enable_processor._session - assert session1 != session2 - session1 = client1.transport.disable_processor._session - session2 = client2.transport.disable_processor._session - assert session1 != session2 - session1 = client1.transport.set_default_processor_version._session - session2 = client2.transport.set_default_processor_version._session - assert session1 != session2 - session1 = client1.transport.review_document._session - session2 = client2.transport.review_document._session - assert session1 != session2 - session1 = client1.transport.evaluate_processor_version._session - session2 = client2.transport.evaluate_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_evaluation._session - session2 = client2.transport.get_evaluation._session - assert session1 != session2 - session1 = client1.transport.list_evaluations._session - session2 = client2.transport.list_evaluations._session - assert session1 != session2 -def test_document_processor_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_document_processor_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_document_processor_service_grpc_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_document_processor_service_grpc_lro_async_client(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -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, processor=processor, ) - actual = DocumentProcessorServiceClient.human_review_config_path(project, location, processor) - assert expected == actual - - -def test_parse_human_review_config_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor": "octopus", - } - path = DocumentProcessorServiceClient.human_review_config_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_human_review_config_path(path) - assert expected == actual - -def test_processor_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - actual = DocumentProcessorServiceClient.processor_path(project, location, processor) - assert expected == actual - - -def test_parse_processor_path(): - expected = { - "project": "mussel", - "location": "winkle", - "processor": "nautilus", - } - path = DocumentProcessorServiceClient.processor_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_path(path) - assert expected == actual - -def test_processor_type_path(): - project = "scallop" - location = "abalone" - processor_type = "squid" - expected = "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - actual = DocumentProcessorServiceClient.processor_type_path(project, location, processor_type) - assert expected == actual - - -def test_parse_processor_type_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor_type": "octopus", - } - path = DocumentProcessorServiceClient.processor_type_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_type_path(path) - assert expected == actual - -def test_processor_version_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - processor_version = "mussel" - expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - actual = DocumentProcessorServiceClient.processor_version_path(project, location, processor, processor_version) - assert expected == actual - - -def test_parse_processor_version_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "processor": "scallop", - "processor_version": "abalone", - } - path = DocumentProcessorServiceClient.processor_version_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentProcessorServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DocumentProcessorServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentProcessorServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DocumentProcessorServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentProcessorServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DocumentProcessorServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DocumentProcessorServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DocumentProcessorServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentProcessorServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DocumentProcessorServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentProcessorServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py b/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py rename to samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py diff --git a/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json index fe28a6f0..96d60af2 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.12.0" + "version": "0.1.0" }, "snippets": [ { @@ -1130,6 +1130,167 @@ ], "title": "documentai_v1_generated_document_processor_service_enable_processor_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.evaluate_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EvaluateProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_evaluate_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_evaluate_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.evaluate_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EvaluateProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_evaluate_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_evaluate_processor_version_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1291,6 +1452,167 @@ ], "title": "documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_evaluation", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "documentai_v1_generated_document_processor_service_get_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_get_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_evaluation", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "documentai_v1_generated_document_processor_service_get_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_get_evaluation_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1330,14 +1652,175 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1.types.ProcessorType", - "shortName": "get_processor_type" + "resultType": "google.cloud.documentai_v1.types.ProcessorType", + "shortName": "get_processor_type" + }, + "description": "Sample for GetProcessorType", + "file": "documentai_v1_generated_document_processor_service_get_processor_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_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_v1_generated_document_processor_service_get_processor_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_type", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" + }, + { + "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_v1.types.ProcessorType", + "shortName": "get_processor_type" + }, + "description": "Sample for GetProcessorType", + "file": "documentai_v1_generated_document_processor_service_get_processor_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_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_v1_generated_document_processor_service_get_processor_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.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_v1.types.ProcessorVersion", + "shortName": "get_processor_version" }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1_generated_document_processor_service_get_processor_type_async.py", + "description": "Sample for GetProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_get_processor_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_async", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_async", "segments": [ { "end": 51, @@ -1370,7 +1853,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1_generated_document_processor_service_get_processor_type_async.py" + "title": "documentai_v1_generated_document_processor_service_get_processor_version_async.py" }, { "canonical": true, @@ -1379,19 +1862,19 @@ "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", "shortName": "DocumentProcessorServiceClient" }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_type", + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_version", "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", "service": { "fullName": "google.cloud.documentai.v1.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessorType" + "shortName": "GetProcessorVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" + "type": "google.cloud.documentai_v1.types.GetProcessorVersionRequest" }, { "name": "name", @@ -1410,14 +1893,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1.types.ProcessorType", - "shortName": "get_processor_type" + "resultType": "google.cloud.documentai_v1.types.ProcessorVersion", + "shortName": "get_processor_version" }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1_generated_document_processor_service_get_processor_type_sync.py", + "description": "Sample for GetProcessorVersion", + "file": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_sync", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_sync", "segments": [ { "end": 51, @@ -1450,7 +1933,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1_generated_document_processor_service_get_processor_type_sync.py" + "title": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py" }, { "canonical": true, @@ -1460,19 +1943,19 @@ "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", "shortName": "DocumentProcessorServiceAsyncClient" }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_version", + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor", "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", "service": { "fullName": "google.cloud.documentai.v1.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessorVersion" + "shortName": "GetProcessor" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorVersionRequest" + "type": "google.cloud.documentai_v1.types.GetProcessorRequest" }, { "name": "name", @@ -1491,14 +1974,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1.types.ProcessorVersion", - "shortName": "get_processor_version" + "resultType": "google.cloud.documentai_v1.types.Processor", + "shortName": "get_processor" }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_get_processor_version_async.py", + "description": "Sample for GetProcessor", + "file": "documentai_v1_generated_document_processor_service_get_processor_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_async", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_async", "segments": [ { "end": 51, @@ -1531,7 +2014,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1_generated_document_processor_service_get_processor_version_async.py" + "title": "documentai_v1_generated_document_processor_service_get_processor_async.py" }, { "canonical": true, @@ -1540,19 +2023,19 @@ "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", "shortName": "DocumentProcessorServiceClient" }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_version", + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor", "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", "service": { "fullName": "google.cloud.documentai.v1.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessorVersion" + "shortName": "GetProcessor" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorVersionRequest" + "type": "google.cloud.documentai_v1.types.GetProcessorRequest" }, { "name": "name", @@ -1571,14 +2054,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1.types.ProcessorVersion", - "shortName": "get_processor_version" + "resultType": "google.cloud.documentai_v1.types.Processor", + "shortName": "get_processor" }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py", + "description": "Sample for GetProcessor", + "file": "documentai_v1_generated_document_processor_service_get_processor_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_sync", + "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_sync", "segments": [ { "end": 51, @@ -1611,7 +2094,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py" + "title": "documentai_v1_generated_document_processor_service_get_processor_sync.py" }, { "canonical": true, @@ -1621,22 +2104,22 @@ "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", "shortName": "DocumentProcessorServiceAsyncClient" }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor", + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_evaluations", "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", "service": { "fullName": "google.cloud.documentai.v1.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessor" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorRequest" + "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1652,22 +2135,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "get_processor" + "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" }, - "description": "Sample for GetProcessor", - "file": "documentai_v1_generated_document_processor_service_get_processor_async.py", + "description": "Sample for ListEvaluations", + "file": "documentai_v1_generated_document_processor_service_list_evaluations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_async", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1687,12 +2170,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1_generated_document_processor_service_get_processor_async.py" + "title": "documentai_v1_generated_document_processor_service_list_evaluations_async.py" }, { "canonical": true, @@ -1701,22 +2184,22 @@ "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", "shortName": "DocumentProcessorServiceClient" }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor", + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_evaluations", "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", "service": { "fullName": "google.cloud.documentai.v1.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessor" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorRequest" + "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1732,22 +2215,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "get_processor" + "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" }, - "description": "Sample for GetProcessor", - "file": "documentai_v1_generated_document_processor_service_get_processor_sync.py", + "description": "Sample for ListEvaluations", + "file": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_sync", + "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1767,12 +2250,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1_generated_document_processor_service_get_processor_sync.py" + "title": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py" }, { "canonical": true, @@ -2732,6 +3215,175 @@ ], "title": "documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.train_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "TrainProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor_version", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_train_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_train_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.train_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "TrainProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor_version", + "type": "google.cloud.documentai_v1.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_v1_generated_document_processor_service_train_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1_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_v1_generated_document_processor_service_train_processor_version_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json index bd0b6d31..ef56bd7e 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.12.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json b/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json index 0fc04ebf..f02752f1 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.12.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/scripts/fixup_documentai_v1_keywords.py b/scripts/fixup_documentai_v1_keywords.py index 465e9dd8..090486ac 100644 --- a/scripts/fixup_documentai_v1_keywords.py +++ b/scripts/fixup_documentai_v1_keywords.py @@ -46,16 +46,20 @@ 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_type': ('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', 'skip_human_review', 'field_mask', ), 'review_document': ('human_review_config', 'inline_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/tests/unit/gapic/documentai_v1/test_document_processor_service.py b/tests/unit/gapic/documentai_v1/test_document_processor_service.py index 3c1469a4..99def329 100644 --- a/tests/unit/gapic/documentai_v1/test_document_processor_service.py +++ b/tests/unit/gapic/documentai_v1/test_document_processor_service.py @@ -78,6 +78,7 @@ document_io, document_processor_service, document_schema, + evaluation, geometry, ) from google.cloud.documentai_v1.types import processor @@ -2882,6 +2883,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", [ @@ -5494,50 +5746,2128 @@ async def test_review_document_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.ProcessRequest, + document_processor_service.EvaluateProcessorVersionRequest, dict, ], ) -def test_process_document_rest(request_type): +def test_evaluate_processor_version(request_type, transport: str = "grpc"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() + # 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() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_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: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.evaluate_processor_version(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.process_document(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, document_processor_service.ProcessResponse) + assert isinstance(response, future.Future) -def test_process_document_rest_required_fields( - request_type=document_processor_service.ProcessRequest, -): - transport_class = transports.DocumentProcessorServiceRestTransport +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", + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( + # 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 + + +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.ProcessRequest, + dict, + ], +) +def test_process_document_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.process_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.ProcessResponse) + + +def test_process_document_rest_required_fields( + request_type=document_processor_service.ProcessRequest, +): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).process_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).process_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ProcessResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.process_document(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_process_document_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.process_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_process_document_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, "post_process_document" + ) as post, mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, "pre_process_document" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ProcessRequest.pb( + document_processor_service.ProcessRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_processor_service.ProcessResponse.to_json( + document_processor_service.ProcessResponse() + ) + + request = document_processor_service.ProcessRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ProcessResponse() + + client.process_document( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_process_document_rest_bad_request( + transport: str = "rest", request_type=document_processor_service.ProcessRequest +): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.process_document(request) + + +def test_process_document_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ProcessResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/processors/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.process_document(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/processors/*}:process" + % client.transport._host, + args[1], + ) + + +def test_process_document_rest_flattened_error(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.process_document( + document_processor_service.ProcessRequest(), + name="name_value", + ) + + +def test_process_document_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.BatchProcessRequest, + dict, + ], +) +def test_batch_process_documents_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_process_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_process_documents_rest_required_fields( + request_type=document_processor_service.BatchProcessRequest, +): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_process_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_process_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_process_documents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_process_documents_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_process_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_process_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, + "post_batch_process_documents", + ) as post, mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, + "pre_batch_process_documents", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.BatchProcessRequest.pb( + document_processor_service.BatchProcessRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = document_processor_service.BatchProcessRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_process_documents( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_process_documents_rest_bad_request( + transport: str = "rest", request_type=document_processor_service.BatchProcessRequest +): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_process_documents(request) + + +def test_batch_process_documents_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/processors/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.batch_process_documents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/processors/*}:batchProcess" + % client.transport._host, + args[1], + ) + + +def test_batch_process_documents_rest_flattened_error(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_process_documents( + document_processor_service.BatchProcessRequest(), + name="name_value", + ) + + +def test_batch_process_documents_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.FetchProcessorTypesRequest, + dict, + ], +) +def test_fetch_processor_types_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.fetch_processor_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) + + +def test_fetch_processor_types_rest_required_fields( + request_type=document_processor_service.FetchProcessorTypesRequest, +): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.fetch_processor_types(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_fetch_processor_types_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_processor_types_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types" + ) as post, mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.FetchProcessorTypesRequest.pb( + document_processor_service.FetchProcessorTypesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + document_processor_service.FetchProcessorTypesResponse.to_json( + document_processor_service.FetchProcessorTypesResponse() + ) + ) + + request = document_processor_service.FetchProcessorTypesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.FetchProcessorTypesResponse() + + client.fetch_processor_types( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_processor_types_rest_bad_request( + transport: str = "rest", + request_type=document_processor_service.FetchProcessorTypesRequest, +): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_processor_types(request) + + +def test_fetch_processor_types_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.FetchProcessorTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.fetch_processor_types(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}:fetchProcessorTypes" + % client.transport._host, + args[1], + ) + + +def test_fetch_processor_types_rest_flattened_error(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_processor_types( + document_processor_service.FetchProcessorTypesRequest(), + parent="parent_value", + ) + + +def test_fetch_processor_types_rest_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.ListProcessorTypesRequest, + dict, + ], +) +def test_list_processor_types_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_processor_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorTypesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_processor_types_rest_required_fields( + request_type=document_processor_service.ListProcessorTypesRequest, +): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_processor_types._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_processor_types._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_processor_types(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_processor_types_rest_unset_required_fields(): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_processor_types._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processor_types_rest_interceptors(null_interceptor): + transport = transports.DocumentProcessorServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DocumentProcessorServiceRestInterceptor(), + ) + client = DocumentProcessorServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types" + ) as post, mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_processor_service.ListProcessorTypesRequest.pb( + document_processor_service.ListProcessorTypesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + document_processor_service.ListProcessorTypesResponse.to_json( + document_processor_service.ListProcessorTypesResponse() + ) + ) + + request = document_processor_service.ListProcessorTypesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_processor_service.ListProcessorTypesResponse() + + client.list_processor_types( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processor_types_rest_bad_request( + transport: str = "rest", + request_type=document_processor_service.ListProcessorTypesRequest, +): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processor_types(request) + + +def test_list_processor_types_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = document_processor_service.ListProcessorTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = document_processor_service.ListProcessorTypesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_processor_types(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/processorTypes" + % client.transport._host, + args[1], + ) + + +def test_list_processor_types_rest_flattened_error(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processor_types( + document_processor_service.ListProcessorTypesRequest(), + parent="parent_value", + ) + + +def test_list_processor_types_rest_pager(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + next_page_token="abc", + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[], + next_page_token="def", + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + ], + next_page_token="ghi", + ), + document_processor_service.ListProcessorTypesResponse( + processor_types=[ + processor_type.ProcessorType(), + processor_type.ProcessorType(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + document_processor_service.ListProcessorTypesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_processor_types(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor_type.ProcessorType) for i in results) + + pages = list(client.list_processor_types(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.GetProcessorTypeRequest, + dict, + ], +) +def test_get_processor_type_rest(request_type): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/processorTypes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = processor_type.ProcessorType( + name="name_value", + type_="type__value", + category="category_value", + allow_creation=True, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + sample_document_uris=["sample_document_uris_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = processor_type.ProcessorType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_processor_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, processor_type.ProcessorType) + assert response.name == "name_value" + assert response.type_ == "type__value" + assert response.category == "category_value" + assert response.allow_creation is True + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.sample_document_uris == ["sample_document_uris_value"] + + +def test_get_processor_type_rest_required_fields( + request_type=document_processor_service.GetProcessorTypeRequest, +): + transport_class = transports.DocumentProcessorServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( pb_request, including_default_value_fields=False, use_integers_for_enums=False, @@ -5548,7 +7878,7 @@ def test_process_document_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).process_document._get_unset_required_fields(jsonified_request) + ).get_processor_type._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5557,7 +7887,7 @@ def test_process_document_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).process_document._get_unset_required_fields(jsonified_request) + ).get_processor_type._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -5571,7 +7901,7 @@ def test_process_document_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() + return_value = processor_type.ProcessorType() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5583,41 +7913,38 @@ def test_process_document_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ProcessResponse.pb( - return_value - ) + pb_return_value = processor_type.ProcessorType.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.process_document(request) + response = client.get_processor_type(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_process_document_rest_unset_required_fields(): +def test_get_processor_type_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.process_document._get_unset_required_fields({}) + unset_fields = transport.get_processor_type._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_process_document_rest_interceptors(null_interceptor): +def test_get_processor_type_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -5630,14 +7957,14 @@ def test_process_document_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_process_document" + transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_process_document" + transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.ProcessRequest.pb( - document_processor_service.ProcessRequest() + pb_message = document_processor_service.GetProcessorTypeRequest.pb( + document_processor_service.GetProcessorTypeRequest() ) transcode.return_value = { "method": "post", @@ -5649,19 +7976,19 @@ def test_process_document_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ProcessResponse.to_json( - document_processor_service.ProcessResponse() + req.return_value._content = processor_type.ProcessorType.to_json( + processor_type.ProcessorType() ) - request = document_processor_service.ProcessRequest() + request = document_processor_service.GetProcessorTypeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = document_processor_service.ProcessResponse() + post.return_value = processor_type.ProcessorType() - client.process_document( + client.get_processor_type( request, metadata=[ ("key", "val"), @@ -5673,8 +8000,9 @@ def test_process_document_rest_interceptors(null_interceptor): post.assert_called_once() -def test_process_document_rest_bad_request( - transport: str = "rest", request_type=document_processor_service.ProcessRequest +def test_get_processor_type_rest_bad_request( + transport: str = "rest", + request_type=document_processor_service.GetProcessorTypeRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5682,7 +8010,7 @@ def test_process_document_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/processorTypes/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5694,10 +8022,10 @@ def test_process_document_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.process_document(request) + client.get_processor_type(request) -def test_process_document_rest_flattened(): +def test_get_processor_type_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5706,11 +8034,11 @@ def test_process_document_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() + return_value = processor_type.ProcessorType() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/processors/sample3" + "name": "projects/sample1/locations/sample2/processorTypes/sample3" } # get truthy value for each flattened field @@ -5722,25 +8050,25 @@ def test_process_document_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ProcessResponse.pb(return_value) + pb_return_value = processor_type.ProcessorType.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.process_document(**mock_args) + client.get_processor_type(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*}:process" + "%s/v1/{name=projects/*/locations/*/processorTypes/*}" % client.transport._host, args[1], ) -def test_process_document_rest_flattened_error(transport: str = "rest"): +def test_get_processor_type_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5749,13 +8077,13 @@ def test_process_document_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.process_document( - document_processor_service.ProcessRequest(), + client.get_processor_type( + document_processor_service.GetProcessorTypeRequest(), name="name_value", ) -def test_process_document_rest_error(): +def test_get_processor_type_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -5764,45 +8092,51 @@ def test_process_document_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.BatchProcessRequest, + document_processor_service.ListProcessorsRequest, dict, ], ) -def test_batch_process_documents_rest(request_type): +def test_list_processors_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = document_processor_service.ListProcessorsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = document_processor_service.ListProcessorsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_process_documents(request) + response = client.list_processors(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == "next_page_token_value" -def test_batch_process_documents_rest_required_fields( - request_type=document_processor_service.BatchProcessRequest, +def test_list_processors_rest_required_fields( + request_type=document_processor_service.ListProcessorsRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5817,21 +8151,28 @@ def test_batch_process_documents_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_process_documents._get_unset_required_fields(jsonified_request) + ).list_processors._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_process_documents._get_unset_required_fields(jsonified_request) + ).list_processors._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5840,7 +8181,7 @@ def test_batch_process_documents_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = document_processor_service.ListProcessorsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5852,37 +8193,48 @@ def test_batch_process_documents_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = document_processor_service.ListProcessorsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_process_documents(request) + response = client.list_processors(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_process_documents_rest_unset_required_fields(): +def test_list_processors_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_process_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_processors._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_process_documents_rest_interceptors(null_interceptor): +def test_list_processors_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -5895,18 +8247,14 @@ def test_batch_process_documents_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "post_batch_process_documents", + transports.DocumentProcessorServiceRestInterceptor, "post_list_processors" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "pre_batch_process_documents", + transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.BatchProcessRequest.pb( - document_processor_service.BatchProcessRequest() + pb_message = document_processor_service.ListProcessorsRequest.pb( + document_processor_service.ListProcessorsRequest() ) transcode.return_value = { "method": "post", @@ -5918,19 +8266,21 @@ def test_batch_process_documents_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = ( + document_processor_service.ListProcessorsResponse.to_json( + document_processor_service.ListProcessorsResponse() + ) ) - request = document_processor_service.BatchProcessRequest() + request = document_processor_service.ListProcessorsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = document_processor_service.ListProcessorsResponse() - client.batch_process_documents( + client.list_processors( request, metadata=[ ("key", "val"), @@ -5942,8 +8292,9 @@ def test_batch_process_documents_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_process_documents_rest_bad_request( - transport: str = "rest", request_type=document_processor_service.BatchProcessRequest +def test_list_processors_rest_bad_request( + transport: str = "rest", + request_type=document_processor_service.ListProcessorsRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5951,7 +8302,7 @@ def test_batch_process_documents_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5963,10 +8314,10 @@ def test_batch_process_documents_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_process_documents(request) + client.list_processors(request) -def test_batch_process_documents_rest_flattened(): +def test_list_processors_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5975,40 +8326,40 @@ def test_batch_process_documents_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = document_processor_service.ListProcessorsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/processors/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = document_processor_service.ListProcessorsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.batch_process_documents(**mock_args) + client.list_processors(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*}:batchProcess" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1], ) -def test_batch_process_documents_rest_flattened_error(transport: str = "rest"): +def test_list_processors_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6017,63 +8368,134 @@ def test_batch_process_documents_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name="name_value", + client.list_processors( + document_processor_service.ListProcessorsRequest(), + parent="parent_value", ) -def test_batch_process_documents_rest_error(): +def test_list_processors_rest_pager(transport: str = "rest"): client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + processor.Processor(), + ], + next_page_token="abc", + ), + document_processor_service.ListProcessorsResponse( + processors=[], + next_page_token="def", + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + ], + next_page_token="ghi", + ), + document_processor_service.ListProcessorsResponse( + processors=[ + processor.Processor(), + processor.Processor(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + document_processor_service.ListProcessorsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_processors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, processor.Processor) for i in results) + + pages = list(client.list_processors(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - document_processor_service.FetchProcessorTypesRequest, + document_processor_service.GetProcessorRequest, dict, ], ) -def test_fetch_processor_types_rest(request_type): +def test_get_processor_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() + return_value = processor.Processor( + name="name_value", + type_="type__value", + display_name="display_name_value", + state=processor.Processor.State.ENABLED, + default_processor_version="default_processor_version_value", + process_endpoint="process_endpoint_value", + kms_key_name="kms_key_name_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb( - return_value - ) + pb_return_value = processor.Processor.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_processor_types(request) + response = client.get_processor(request) # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - + assert isinstance(response, processor.Processor) + assert response.name == "name_value" + assert response.type_ == "type__value" + assert response.display_name == "display_name_value" + assert response.state == processor.Processor.State.ENABLED + assert response.default_processor_version == "default_processor_version_value" + assert response.process_endpoint == "process_endpoint_value" + assert response.kms_key_name == "kms_key_name_value" -def test_fetch_processor_types_rest_required_fields( - request_type=document_processor_service.FetchProcessorTypesRequest, + +def test_get_processor_rest_required_fields( + request_type=document_processor_service.GetProcessorRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6088,21 +8510,21 @@ def test_fetch_processor_types_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_processor_types._get_unset_required_fields(jsonified_request) + ).get_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_processor_types._get_unset_required_fields(jsonified_request) + ).get_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6111,7 +8533,7 @@ def test_fetch_processor_types_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() + return_value = processor.Processor() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6131,32 +8553,30 @@ def test_fetch_processor_types_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb( - return_value - ) + pb_return_value = processor.Processor.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_processor_types(request) + response = client.get_processor(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_fetch_processor_types_rest_unset_required_fields(): +def test_get_processor_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent",))) + unset_fields = transport.get_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_processor_types_rest_interceptors(null_interceptor): +def test_get_processor_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6169,14 +8589,14 @@ def test_fetch_processor_types_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types" + transports.DocumentProcessorServiceRestInterceptor, "post_get_processor" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types" + transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.FetchProcessorTypesRequest.pb( - document_processor_service.FetchProcessorTypesRequest() + pb_message = document_processor_service.GetProcessorRequest.pb( + document_processor_service.GetProcessorRequest() ) transcode.return_value = { "method": "post", @@ -6188,21 +8608,17 @@ def test_fetch_processor_types_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - document_processor_service.FetchProcessorTypesResponse.to_json( - document_processor_service.FetchProcessorTypesResponse() - ) - ) + req.return_value._content = processor.Processor.to_json(processor.Processor()) - request = document_processor_service.FetchProcessorTypesRequest() + request = document_processor_service.GetProcessorRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = document_processor_service.FetchProcessorTypesResponse() + post.return_value = processor.Processor() - client.fetch_processor_types( + client.get_processor( request, metadata=[ ("key", "val"), @@ -6214,9 +8630,8 @@ def test_fetch_processor_types_rest_interceptors(null_interceptor): post.assert_called_once() -def test_fetch_processor_types_rest_bad_request( - transport: str = "rest", - request_type=document_processor_service.FetchProcessorTypesRequest, +def test_get_processor_rest_bad_request( + transport: str = "rest", request_type=document_processor_service.GetProcessorRequest ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6224,7 +8639,7 @@ def test_fetch_processor_types_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6236,10 +8651,10 @@ def test_fetch_processor_types_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.fetch_processor_types(request) + client.get_processor(request) -def test_fetch_processor_types_rest_flattened(): +def test_get_processor_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6248,41 +8663,40 @@ def test_fetch_processor_types_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() + return_value = processor.Processor() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/processors/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.FetchProcessorTypesResponse.pb( - return_value - ) + pb_return_value = processor.Processor.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.fetch_processor_types(**mock_args) + client.get_processor(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}:fetchProcessorTypes" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1], ) -def test_fetch_processor_types_rest_flattened_error(transport: str = "rest"): +def test_get_processor_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6291,13 +8705,13 @@ def test_fetch_processor_types_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent="parent_value", + client.get_processor( + document_processor_service.GetProcessorRequest(), + name="name_value", ) -def test_fetch_processor_types_rest_error(): +def test_get_processor_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6306,46 +8720,40 @@ def test_fetch_processor_types_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.ListProcessorTypesRequest, + document_processor_service.TrainProcessorVersionRequest, dict, ], ) -def test_list_processor_types_rest(request_type): +def test_train_processor_version_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse( - next_page_token="next_page_token_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_processor_types(request) + response = client.train_processor_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesPager) - assert response.next_page_token == "next_page_token_value" + assert response.operation.name == "operations/spam" -def test_list_processor_types_rest_required_fields( - request_type=document_processor_service.ListProcessorTypesRequest, +def test_train_processor_version_rest_required_fields( + request_type=document_processor_service.TrainProcessorVersionRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport @@ -6365,7 +8773,7 @@ def test_list_processor_types_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_processor_types._get_unset_required_fields(jsonified_request) + ).train_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6374,14 +8782,7 @@ def test_list_processor_types_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_processor_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).train_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6395,7 +8796,7 @@ def test_list_processor_types_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6407,48 +8808,45 @@ def test_list_processor_types_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_processor_types(request) + response = client.train_processor_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_processor_types_rest_unset_required_fields(): +def test_train_processor_version_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_processor_types._get_unset_required_fields({}) + unset_fields = transport.train_processor_version._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "parent", + "processorVersion", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_types_rest_interceptors(null_interceptor): +def test_train_processor_version_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6461,14 +8859,18 @@ def test_list_processor_types_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, + "post_train_processor_version", ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types" + transports.DocumentProcessorServiceRestInterceptor, + "pre_train_processor_version", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.ListProcessorTypesRequest.pb( - document_processor_service.ListProcessorTypesRequest() + pb_message = document_processor_service.TrainProcessorVersionRequest.pb( + document_processor_service.TrainProcessorVersionRequest() ) transcode.return_value = { "method": "post", @@ -6480,21 +8882,19 @@ def test_list_processor_types_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - document_processor_service.ListProcessorTypesResponse.to_json( - document_processor_service.ListProcessorTypesResponse() - ) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = document_processor_service.ListProcessorTypesRequest() + request = document_processor_service.TrainProcessorVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorTypesResponse() + post.return_value = operations_pb2.Operation() - client.list_processor_types( + client.train_processor_version( request, metadata=[ ("key", "val"), @@ -6506,9 +8906,9 @@ def test_list_processor_types_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_processor_types_rest_bad_request( +def test_train_processor_version_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.ListProcessorTypesRequest, + request_type=document_processor_service.TrainProcessorVersionRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6516,7 +8916,7 @@ def test_list_processor_types_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6528,10 +8928,10 @@ def test_list_processor_types_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_processor_types(request) + client.train_processor_version(request) -def test_list_processor_types_rest_flattened(): +def test_train_processor_version_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6540,41 +8940,41 @@ def test_list_processor_types_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/processors/sample3" + } # get truthy value for each flattened field mock_args = dict( parent="parent_value", + processor_version=processor.ProcessorVersion(name="name_value"), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorTypesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_processor_types(**mock_args) + client.train_processor_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/processorTypes" + "%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train" % client.transport._host, args[1], ) -def test_list_processor_types_rest_flattened_error(transport: str = "rest"): +def test_train_processor_version_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6583,127 +8983,72 @@ def test_list_processor_types_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_processor_types( - document_processor_service.ListProcessorTypesRequest(), + client.train_processor_version( + document_processor_service.TrainProcessorVersionRequest(), parent="parent_value", + processor_version=processor.ProcessorVersion(name="name_value"), ) -def test_list_processor_types_rest_pager(transport: str = "rest"): +def test_train_processor_version_rest_error(): client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token="abc", - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token="def", - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token="ghi", - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - document_processor_service.ListProcessorTypesResponse.to_json(x) - for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_processor_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor_type.ProcessorType) for i in results) - - pages = list(client.list_processor_types(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - document_processor_service.GetProcessorTypeRequest, + document_processor_service.GetProcessorVersionRequest, dict, ], ) -def test_get_processor_type_rest(request_type): +def test_get_processor_version_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processorTypes/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType( - name="name_value", - type_="type__value", - category="category_value", - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=["sample_document_uris_value"], + # Designate an appropriate value for the returned response. + return_value = processor.ProcessorVersion( + name="name_value", + display_name="display_name_value", + state=processor.ProcessorVersion.State.DEPLOYED, + kms_key_name="kms_key_name_value", + kms_key_version_name="kms_key_version_name_value", + google_managed=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = processor_type.ProcessorType.pb(return_value) + pb_return_value = processor.ProcessorVersion.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_processor_type(request) + response = client.get_processor_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) + assert isinstance(response, processor.ProcessorVersion) assert response.name == "name_value" - assert response.type_ == "type__value" - assert response.category == "category_value" - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ["sample_document_uris_value"] + assert response.display_name == "display_name_value" + assert response.state == processor.ProcessorVersion.State.DEPLOYED + assert response.kms_key_name == "kms_key_name_value" + assert response.kms_key_version_name == "kms_key_version_name_value" + assert response.google_managed is True -def test_get_processor_type_rest_required_fields( - request_type=document_processor_service.GetProcessorTypeRequest, +def test_get_processor_version_rest_required_fields( + request_type=document_processor_service.GetProcessorVersionRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport @@ -6723,7 +9068,7 @@ def test_get_processor_type_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_processor_type._get_unset_required_fields(jsonified_request) + ).get_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6732,7 +9077,7 @@ def test_get_processor_type_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_processor_type._get_unset_required_fields(jsonified_request) + ).get_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6746,7 +9091,7 @@ def test_get_processor_type_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() + return_value = processor.ProcessorVersion() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6766,30 +9111,30 @@ def test_get_processor_type_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = processor_type.ProcessorType.pb(return_value) + pb_return_value = processor.ProcessorVersion.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_processor_type(request) + response = client.get_processor_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_processor_type_rest_unset_required_fields(): +def test_get_processor_version_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_processor_type._get_unset_required_fields({}) + unset_fields = transport.get_processor_version._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_type_rest_interceptors(null_interceptor): +def test_get_processor_version_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6802,14 +9147,14 @@ def test_get_processor_type_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type" + transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type" + transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.GetProcessorTypeRequest.pb( - document_processor_service.GetProcessorTypeRequest() + pb_message = document_processor_service.GetProcessorVersionRequest.pb( + document_processor_service.GetProcessorVersionRequest() ) transcode.return_value = { "method": "post", @@ -6821,19 +9166,19 @@ def test_get_processor_type_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = processor_type.ProcessorType.to_json( - processor_type.ProcessorType() + req.return_value._content = processor.ProcessorVersion.to_json( + processor.ProcessorVersion() ) - request = document_processor_service.GetProcessorTypeRequest() + request = document_processor_service.GetProcessorVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = processor_type.ProcessorType() + post.return_value = processor.ProcessorVersion() - client.get_processor_type( + client.get_processor_version( request, metadata=[ ("key", "val"), @@ -6845,9 +9190,9 @@ def test_get_processor_type_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_processor_type_rest_bad_request( +def test_get_processor_version_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.GetProcessorTypeRequest, + request_type=document_processor_service.GetProcessorVersionRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6855,7 +9200,9 @@ def test_get_processor_type_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processorTypes/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6867,10 +9214,10 @@ def test_get_processor_type_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_processor_type(request) + client.get_processor_version(request) -def test_get_processor_type_rest_flattened(): +def test_get_processor_version_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6879,11 +9226,11 @@ def test_get_processor_type_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() + return_value = processor.ProcessorVersion() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/processorTypes/sample3" + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" } # get truthy value for each flattened field @@ -6895,25 +9242,25 @@ def test_get_processor_type_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = processor_type.ProcessorType.pb(return_value) + pb_return_value = processor.ProcessorVersion.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_processor_type(**mock_args) + client.get_processor_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processorTypes/*}" + "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1], ) -def test_get_processor_type_rest_flattened_error(transport: str = "rest"): +def test_get_processor_version_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6922,13 +9269,13 @@ def test_get_processor_type_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), + client.get_processor_version( + document_processor_service.GetProcessorVersionRequest(), name="name_value", ) -def test_get_processor_type_rest_error(): +def test_get_processor_version_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6937,46 +9284,46 @@ def test_get_processor_type_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.ListProcessorsRequest, + document_processor_service.ListProcessorVersionsRequest, dict, ], ) -def test_list_processors_rest(request_type): +def test_list_processor_versions_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse( + return_value = document_processor_service.ListProcessorVersionsResponse( next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorsResponse.pb( + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb( return_value ) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_processors(request) + response = client.list_processor_versions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) + assert isinstance(response, pagers.ListProcessorVersionsPager) assert response.next_page_token == "next_page_token_value" -def test_list_processors_rest_required_fields( - request_type=document_processor_service.ListProcessorsRequest, +def test_list_processor_versions_rest_required_fields( + request_type=document_processor_service.ListProcessorVersionsRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport @@ -6996,7 +9343,7 @@ def test_list_processors_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_processors._get_unset_required_fields(jsonified_request) + ).list_processor_versions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -7005,7 +9352,7 @@ def test_list_processors_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_processors._get_unset_required_fields(jsonified_request) + ).list_processor_versions._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -7026,7 +9373,7 @@ def test_list_processors_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() + return_value = document_processor_service.ListProcessorVersionsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7046,27 +9393,29 @@ def test_list_processors_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorsResponse.pb( - return_value + pb_return_value = ( + document_processor_service.ListProcessorVersionsResponse.pb( + return_value + ) ) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_processors(request) + response = client.list_processor_versions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_processors_rest_unset_required_fields(): +def test_list_processor_versions_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_processors._get_unset_required_fields({}) + unset_fields = transport.list_processor_versions._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -7079,7 +9428,7 @@ def test_list_processors_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processors_rest_interceptors(null_interceptor): +def test_list_processor_versions_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7092,14 +9441,16 @@ def test_list_processors_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_list_processors" + transports.DocumentProcessorServiceRestInterceptor, + "post_list_processor_versions", ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors" + transports.DocumentProcessorServiceRestInterceptor, + "pre_list_processor_versions", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.ListProcessorsRequest.pb( - document_processor_service.ListProcessorsRequest() + pb_message = document_processor_service.ListProcessorVersionsRequest.pb( + document_processor_service.ListProcessorVersionsRequest() ) transcode.return_value = { "method": "post", @@ -7112,20 +9463,20 @@ def test_list_processors_rest_interceptors(null_interceptor): req.return_value.status_code = 200 req.return_value.request = PreparedRequest() req.return_value._content = ( - document_processor_service.ListProcessorsResponse.to_json( - document_processor_service.ListProcessorsResponse() + document_processor_service.ListProcessorVersionsResponse.to_json( + document_processor_service.ListProcessorVersionsResponse() ) ) - request = document_processor_service.ListProcessorsRequest() + request = document_processor_service.ListProcessorVersionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorsResponse() + post.return_value = document_processor_service.ListProcessorVersionsResponse() - client.list_processors( + client.list_processor_versions( request, metadata=[ ("key", "val"), @@ -7137,9 +9488,9 @@ def test_list_processors_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_processors_rest_bad_request( +def test_list_processor_versions_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.ListProcessorsRequest, + request_type=document_processor_service.ListProcessorVersionsRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7147,7 +9498,7 @@ def test_list_processors_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -7159,10 +9510,10 @@ def test_list_processors_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_processors(request) + client.list_processor_versions(request) -def test_list_processors_rest_flattened(): +def test_list_processor_versions_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7171,10 +9522,12 @@ def test_list_processors_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() + return_value = document_processor_service.ListProcessorVersionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/processors/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -7185,26 +9538,27 @@ def test_list_processors_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorsResponse.pb( + pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb( return_value ) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_processors(**mock_args) + client.list_processor_versions(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions" + % client.transport._host, args[1], ) -def test_list_processors_rest_flattened_error(transport: str = "rest"): +def test_list_processor_versions_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7213,13 +9567,13 @@ def test_list_processors_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_processors( - document_processor_service.ListProcessorsRequest(), + client.list_processor_versions( + document_processor_service.ListProcessorVersionsRequest(), parent="parent_value", ) -def test_list_processors_rest_pager(transport: str = "rest"): +def test_list_processor_versions_rest_pager(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7231,28 +9585,28 @@ def test_list_processors_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), + processor.ProcessorVersion(), ], next_page_token="abc", ), - document_processor_service.ListProcessorsResponse( - processors=[], + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[], next_page_token="def", ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), ], next_page_token="ghi", ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), + document_processor_service.ListProcessorVersionsResponse( + processor_versions=[ + processor.ProcessorVersion(), + processor.ProcessorVersion(), ], ), ) @@ -7261,7 +9615,7 @@ def test_list_processors_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - document_processor_service.ListProcessorsResponse.to_json(x) + document_processor_service.ListProcessorVersionsResponse.to_json(x) for x in response ) return_values = tuple(Response() for i in response) @@ -7270,15 +9624,17 @@ def test_list_processors_rest_pager(transport: str = "rest"): return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/processors/sample3" + } - pager = client.list_processors(request=sample_request) + pager = client.list_processor_versions(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, processor.Processor) for i in results) + assert all(isinstance(i, processor.ProcessorVersion) for i in results) - pages = list(client.list_processors(request=sample_request).pages) + pages = list(client.list_processor_versions(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -7286,56 +9642,42 @@ def test_list_processors_rest_pager(transport: str = "rest"): @pytest.mark.parametrize( "request_type", [ - document_processor_service.GetProcessorRequest, + document_processor_service.DeleteProcessorVersionRequest, dict, ], ) -def test_get_processor_rest(request_type): +def test_delete_processor_version_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = processor.Processor( - name="name_value", - type_="type__value", - display_name="display_name_value", - state=processor.Processor.State.ENABLED, - default_processor_version="default_processor_version_value", - process_endpoint="process_endpoint_value", - kms_key_name="kms_key_name_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_processor(request) + response = client.delete_processor_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == "name_value" - assert response.type_ == "type__value" - assert response.display_name == "display_name_value" - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == "default_processor_version_value" - assert response.process_endpoint == "process_endpoint_value" - assert response.kms_key_name == "kms_key_name_value" + assert response.operation.name == "operations/spam" -def test_get_processor_rest_required_fields( - request_type=document_processor_service.GetProcessorRequest, +def test_delete_processor_version_rest_required_fields( + request_type=document_processor_service.DeleteProcessorVersionRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport @@ -7355,7 +9697,7 @@ def test_get_processor_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_processor._get_unset_required_fields(jsonified_request) + ).delete_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -7364,7 +9706,7 @@ def test_get_processor_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_processor._get_unset_required_fields(jsonified_request) + ).delete_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -7378,7 +9720,7 @@ def test_get_processor_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = processor.Processor() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7390,38 +9732,36 @@ def test_get_processor_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_processor(request) + response = client.delete_processor_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_processor_rest_unset_required_fields(): +def test_delete_processor_version_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_processor._get_unset_required_fields({}) + unset_fields = transport.delete_processor_version._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_rest_interceptors(null_interceptor): +def test_delete_processor_version_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7434,14 +9774,18 @@ def test_get_processor_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_get_processor" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, + "post_delete_processor_version", ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor" + transports.DocumentProcessorServiceRestInterceptor, + "pre_delete_processor_version", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.GetProcessorRequest.pb( - document_processor_service.GetProcessorRequest() + pb_message = document_processor_service.DeleteProcessorVersionRequest.pb( + document_processor_service.DeleteProcessorVersionRequest() ) transcode.return_value = { "method": "post", @@ -7453,17 +9797,19 @@ def test_get_processor_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = processor.Processor.to_json(processor.Processor()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = document_processor_service.GetProcessorRequest() + request = document_processor_service.DeleteProcessorVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = processor.Processor() + post.return_value = operations_pb2.Operation() - client.get_processor( + client.delete_processor_version( request, metadata=[ ("key", "val"), @@ -7475,8 +9821,9 @@ def test_get_processor_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_processor_rest_bad_request( - transport: str = "rest", request_type=document_processor_service.GetProcessorRequest +def test_delete_processor_version_rest_bad_request( + transport: str = "rest", + request_type=document_processor_service.DeleteProcessorVersionRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7484,7 +9831,9 @@ def test_get_processor_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -7496,10 +9845,10 @@ def test_get_processor_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_processor(request) + client.delete_processor_version(request) -def test_get_processor_rest_flattened(): +def test_delete_processor_version_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7508,11 +9857,11 @@ def test_get_processor_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = processor.Processor() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/processors/sample3" + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" } # get truthy value for each flattened field @@ -7524,24 +9873,24 @@ def test_get_processor_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_processor(**mock_args) + client.delete_processor_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" + % client.transport._host, args[1], ) -def test_get_processor_rest_flattened_error(transport: str = "rest"): +def test_delete_processor_version_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7550,13 +9899,13 @@ def test_get_processor_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_processor( - document_processor_service.GetProcessorRequest(), + client.delete_processor_version( + document_processor_service.DeleteProcessorVersionRequest(), name="name_value", ) -def test_get_processor_rest_error(): +def test_delete_processor_version_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7565,11 +9914,11 @@ def test_get_processor_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.GetProcessorVersionRequest, + document_processor_service.DeployProcessorVersionRequest, dict, ], ) -def test_get_processor_version_rest(request_type): +def test_deploy_processor_version_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7584,37 +9933,23 @@ def test_get_processor_version_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion( - name="name_value", - display_name="display_name_value", - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name="kms_key_name_value", - kms_key_version_name="kms_key_version_name_value", - google_managed=True, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_processor_version(request) + response = client.deploy_processor_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == "kms_key_name_value" - assert response.kms_key_version_name == "kms_key_version_name_value" - assert response.google_managed is True + assert response.operation.name == "operations/spam" -def test_get_processor_version_rest_required_fields( - request_type=document_processor_service.GetProcessorVersionRequest, +def test_deploy_processor_version_rest_required_fields( + request_type=document_processor_service.DeployProcessorVersionRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport @@ -7634,7 +9969,7 @@ def test_get_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_processor_version._get_unset_required_fields(jsonified_request) + ).deploy_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -7643,7 +9978,7 @@ def test_get_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_processor_version._get_unset_required_fields(jsonified_request) + ).deploy_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -7657,7 +9992,7 @@ def test_get_processor_version_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7669,38 +10004,37 @@ def test_get_processor_version_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_processor_version(request) + response = client.deploy_processor_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_processor_version_rest_unset_required_fields(): +def test_deploy_processor_version_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_processor_version._get_unset_required_fields({}) + unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_version_rest_interceptors(null_interceptor): +def test_deploy_processor_version_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7713,14 +10047,18 @@ def test_get_processor_version_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, + "post_deploy_processor_version", ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version" + transports.DocumentProcessorServiceRestInterceptor, + "pre_deploy_processor_version", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.GetProcessorVersionRequest.pb( - document_processor_service.GetProcessorVersionRequest() + pb_message = document_processor_service.DeployProcessorVersionRequest.pb( + document_processor_service.DeployProcessorVersionRequest() ) transcode.return_value = { "method": "post", @@ -7732,19 +10070,19 @@ def test_get_processor_version_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = processor.ProcessorVersion.to_json( - processor.ProcessorVersion() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = document_processor_service.GetProcessorVersionRequest() + request = document_processor_service.DeployProcessorVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = processor.ProcessorVersion() + post.return_value = operations_pb2.Operation() - client.get_processor_version( + client.deploy_processor_version( request, metadata=[ ("key", "val"), @@ -7756,9 +10094,9 @@ def test_get_processor_version_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_processor_version_rest_bad_request( +def test_deploy_processor_version_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.GetProcessorVersionRequest, + request_type=document_processor_service.DeployProcessorVersionRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7780,10 +10118,10 @@ def test_get_processor_version_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_processor_version(request) + client.deploy_processor_version(request) -def test_get_processor_version_rest_flattened(): +def test_deploy_processor_version_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7792,7 +10130,7 @@ def test_get_processor_version_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -7808,25 +10146,24 @@ def test_get_processor_version_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_processor_version(**mock_args) + client.deploy_processor_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" + "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" % client.transport._host, args[1], ) -def test_get_processor_version_rest_flattened_error(transport: str = "rest"): +def test_deploy_processor_version_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7835,13 +10172,13 @@ def test_get_processor_version_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), + client.deploy_processor_version( + document_processor_service.DeployProcessorVersionRequest(), name="name_value", ) -def test_get_processor_version_rest_error(): +def test_deploy_processor_version_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7850,51 +10187,47 @@ def test_get_processor_version_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.ListProcessorVersionsRequest, + document_processor_service.UndeployProcessorVersionRequest, dict, ], ) -def test_list_processor_versions_rest(request_type): +def test_undeploy_processor_version_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse( - next_page_token="next_page_token_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_processor_versions(request) + response = client.undeploy_processor_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsPager) - assert response.next_page_token == "next_page_token_value" + assert response.operation.name == "operations/spam" -def test_list_processor_versions_rest_required_fields( - request_type=document_processor_service.ListProcessorVersionsRequest, +def test_undeploy_processor_version_rest_required_fields( + request_type=document_processor_service.UndeployProcessorVersionRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7909,28 +10242,21 @@ def test_list_processor_versions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_processor_versions._get_unset_required_fields(jsonified_request) + ).undeploy_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_processor_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).undeploy_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7939,7 +10265,7 @@ def test_list_processor_versions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7951,50 +10277,37 @@ def test_list_processor_versions_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = ( - document_processor_service.ListProcessorVersionsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_processor_versions(request) + response = client.undeploy_processor_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_processor_versions_rest_unset_required_fields(): +def test_undeploy_processor_version_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_processor_versions._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_versions_rest_interceptors(null_interceptor): +def test_undeploy_processor_version_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8007,16 +10320,18 @@ def test_list_processor_versions_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( transports.DocumentProcessorServiceRestInterceptor, - "post_list_processor_versions", + "post_undeploy_processor_version", ) as post, mock.patch.object( transports.DocumentProcessorServiceRestInterceptor, - "pre_list_processor_versions", + "pre_undeploy_processor_version", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.ListProcessorVersionsRequest.pb( - document_processor_service.ListProcessorVersionsRequest() + pb_message = document_processor_service.UndeployProcessorVersionRequest.pb( + document_processor_service.UndeployProcessorVersionRequest() ) transcode.return_value = { "method": "post", @@ -8028,21 +10343,19 @@ def test_list_processor_versions_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - document_processor_service.ListProcessorVersionsResponse.to_json( - document_processor_service.ListProcessorVersionsResponse() - ) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = document_processor_service.ListProcessorVersionsRequest() + request = document_processor_service.UndeployProcessorVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorVersionsResponse() + post.return_value = operations_pb2.Operation() - client.list_processor_versions( + client.undeploy_processor_version( request, metadata=[ ("key", "val"), @@ -8054,9 +10367,9 @@ def test_list_processor_versions_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_processor_versions_rest_bad_request( +def test_undeploy_processor_version_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.ListProcessorVersionsRequest, + request_type=document_processor_service.UndeployProcessorVersionRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8064,7 +10377,9 @@ def test_list_processor_versions_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8076,10 +10391,10 @@ def test_list_processor_versions_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_processor_versions(request) + client.undeploy_processor_version(request) -def test_list_processor_versions_rest_flattened(): +def test_undeploy_processor_version_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8088,43 +10403,40 @@ def test_list_processor_versions_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/processors/sample3" + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = document_processor_service.ListProcessorVersionsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_processor_versions(**mock_args) + client.undeploy_processor_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions" + "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" % client.transport._host, args[1], ) -def test_list_processor_versions_rest_flattened_error(transport: str = "rest"): +def test_undeploy_processor_version_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8133,122 +10445,86 @@ def test_list_processor_versions_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent="parent_value", + client.undeploy_processor_version( + document_processor_service.UndeployProcessorVersionRequest(), + name="name_value", ) -def test_list_processor_versions_rest_pager(transport: str = "rest"): +def test_undeploy_processor_version_rest_error(): client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token="abc", - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token="def", - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token="ghi", - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - document_processor_service.ListProcessorVersionsResponse.to_json(x) - for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/processors/sample3" - } - - pager = client.list_processor_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.ProcessorVersion) for i in results) - - pages = list(client.list_processor_versions(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - document_processor_service.DeleteProcessorVersionRequest, + document_processor_service.CreateProcessorRequest, dict, ], ) -def test_delete_processor_version_rest(request_type): +def test_create_processor_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["processor"] = { + "name": "name_value", + "type_": "type__value", + "display_name": "display_name_value", + "state": 1, + "default_processor_version": "default_processor_version_value", + "process_endpoint": "process_endpoint_value", + "create_time": {"seconds": 751, "nanos": 543}, + "kms_key_name": "kms_key_name_value", } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = gcd_processor.Processor( + name="name_value", + type_="type__value", + display_name="display_name_value", + state=gcd_processor.Processor.State.ENABLED, + default_processor_version="default_processor_version_value", + process_endpoint="process_endpoint_value", + kms_key_name="kms_key_name_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_processor_version(request) + response = client.create_processor(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, gcd_processor.Processor) + assert response.name == "name_value" + assert response.type_ == "type__value" + assert response.display_name == "display_name_value" + assert response.state == gcd_processor.Processor.State.ENABLED + assert response.default_processor_version == "default_processor_version_value" + assert response.process_endpoint == "process_endpoint_value" + assert response.kms_key_name == "kms_key_name_value" -def test_delete_processor_version_rest_required_fields( - request_type=document_processor_service.DeleteProcessorVersionRequest, +def test_create_processor_rest_required_fields( + request_type=document_processor_service.CreateProcessorRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8263,21 +10539,21 @@ def test_delete_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_processor_version._get_unset_required_fields(jsonified_request) + ).create_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_processor_version._get_unset_required_fields(jsonified_request) + ).create_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8286,7 +10562,7 @@ def test_delete_processor_version_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = gcd_processor.Processor() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8298,36 +10574,47 @@ def test_delete_processor_version_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_processor_version(request) + response = client.create_processor(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_processor_version_rest_unset_required_fields(): +def test_create_processor_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_processor._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "processor", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_version_rest_interceptors(null_interceptor): +def test_create_processor_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8340,18 +10627,14 @@ def test_delete_processor_version_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "post_delete_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "post_create_processor" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "pre_delete_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorVersionRequest.pb( - document_processor_service.DeleteProcessorVersionRequest() + pb_message = document_processor_service.CreateProcessorRequest.pb( + document_processor_service.CreateProcessorRequest() ) transcode.return_value = { "method": "post", @@ -8363,19 +10646,19 @@ def test_delete_processor_version_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = gcd_processor.Processor.to_json( + gcd_processor.Processor() ) - request = document_processor_service.DeleteProcessorVersionRequest() + request = document_processor_service.CreateProcessorRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = gcd_processor.Processor() - client.delete_processor_version( + client.create_processor( request, metadata=[ ("key", "val"), @@ -8387,9 +10670,9 @@ def test_delete_processor_version_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_processor_version_rest_bad_request( +def test_create_processor_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.DeleteProcessorVersionRequest, + request_type=document_processor_service.CreateProcessorRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8397,8 +10680,16 @@ def test_delete_processor_version_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["processor"] = { + "name": "name_value", + "type_": "type__value", + "display_name": "display_name_value", + "state": 1, + "default_processor_version": "default_processor_version_value", + "process_endpoint": "process_endpoint_value", + "create_time": {"seconds": 751, "nanos": 543}, + "kms_key_name": "kms_key_name_value", } request = request_type(**request_init) @@ -8411,10 +10702,10 @@ def test_delete_processor_version_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_processor_version(request) + client.create_processor(request) -def test_delete_processor_version_rest_flattened(): +def test_create_processor_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8423,40 +10714,39 @@ def test_delete_processor_version_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = gcd_processor.Processor() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + processor=gcd_processor.Processor(name="name_value"), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = gcd_processor.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_processor_version(**mock_args) + client.create_processor(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1], ) -def test_delete_processor_version_rest_flattened_error(transport: str = "rest"): +def test_create_processor_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8465,13 +10755,14 @@ def test_delete_processor_version_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name="name_value", + client.create_processor( + document_processor_service.CreateProcessorRequest(), + parent="parent_value", + processor=gcd_processor.Processor(name="name_value"), ) -def test_delete_processor_version_rest_error(): +def test_create_processor_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8480,20 +10771,18 @@ def test_delete_processor_version_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.DeployProcessorVersionRequest, + document_processor_service.DeleteProcessorRequest, dict, ], ) -def test_deploy_processor_version_rest(request_type): +def test_delete_processor_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -8508,14 +10797,14 @@ def test_deploy_processor_version_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.deploy_processor_version(request) + response = client.delete_processor(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_deploy_processor_version_rest_required_fields( - request_type=document_processor_service.DeployProcessorVersionRequest, +def test_delete_processor_rest_required_fields( + request_type=document_processor_service.DeleteProcessorRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport @@ -8535,7 +10824,7 @@ def test_deploy_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).deploy_processor_version._get_unset_required_fields(jsonified_request) + ).delete_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8544,7 +10833,7 @@ def test_deploy_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).deploy_processor_version._get_unset_required_fields(jsonified_request) + ).delete_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -8570,10 +10859,9 @@ def test_deploy_processor_version_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -8583,24 +10871,24 @@ def test_deploy_processor_version_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.deploy_processor_version(request) + response = client.delete_processor(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_deploy_processor_version_rest_unset_required_fields(): +def test_delete_processor_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) + unset_fields = transport.delete_processor._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_deploy_processor_version_rest_interceptors(null_interceptor): +def test_delete_processor_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8615,16 +10903,14 @@ def test_deploy_processor_version_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "post_deploy_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "pre_deploy_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.DeployProcessorVersionRequest.pb( - document_processor_service.DeployProcessorVersionRequest() + pb_message = document_processor_service.DeleteProcessorRequest.pb( + document_processor_service.DeleteProcessorRequest() ) transcode.return_value = { "method": "post", @@ -8640,7 +10926,7 @@ def test_deploy_processor_version_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = document_processor_service.DeployProcessorVersionRequest() + request = document_processor_service.DeleteProcessorRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8648,7 +10934,7 @@ def test_deploy_processor_version_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.deploy_processor_version( + client.delete_processor( request, metadata=[ ("key", "val"), @@ -8660,9 +10946,9 @@ def test_deploy_processor_version_rest_interceptors(null_interceptor): post.assert_called_once() -def test_deploy_processor_version_rest_bad_request( +def test_delete_processor_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.DeployProcessorVersionRequest, + request_type=document_processor_service.DeleteProcessorRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8670,9 +10956,7 @@ def test_deploy_processor_version_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8684,10 +10968,10 @@ def test_deploy_processor_version_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.deploy_processor_version(request) + client.delete_processor(request) -def test_deploy_processor_version_rest_flattened(): +def test_delete_processor_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8700,7 +10984,7 @@ def test_deploy_processor_version_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + "name": "projects/sample1/locations/sample2/processors/sample3" } # get truthy value for each flattened field @@ -8716,20 +11000,19 @@ def test_deploy_processor_version_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.deploy_processor_version(**mock_args) + client.delete_processor(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1], ) -def test_deploy_processor_version_rest_flattened_error(transport: str = "rest"): +def test_delete_processor_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8738,13 +11021,13 @@ def test_deploy_processor_version_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), + client.delete_processor( + document_processor_service.DeleteProcessorRequest(), name="name_value", ) -def test_deploy_processor_version_rest_error(): +def test_delete_processor_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8753,20 +11036,18 @@ def test_deploy_processor_version_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.UndeployProcessorVersionRequest, + document_processor_service.EnableProcessorRequest, dict, ], ) -def test_undeploy_processor_version_rest(request_type): +def test_enable_processor_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -8781,14 +11062,14 @@ def test_undeploy_processor_version_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.undeploy_processor_version(request) + response = client.enable_processor(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_undeploy_processor_version_rest_required_fields( - request_type=document_processor_service.UndeployProcessorVersionRequest, +def test_enable_processor_rest_required_fields( + request_type=document_processor_service.EnableProcessorRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport @@ -8808,7 +11089,7 @@ def test_undeploy_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).undeploy_processor_version._get_unset_required_fields(jsonified_request) + ).enable_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8817,7 +11098,7 @@ def test_undeploy_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).undeploy_processor_version._get_unset_required_fields(jsonified_request) + ).enable_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -8856,24 +11137,24 @@ def test_undeploy_processor_version_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.undeploy_processor_version(request) + response = client.enable_processor(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_undeploy_processor_version_rest_unset_required_fields(): +def test_enable_processor_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) + unset_fields = transport.enable_processor._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undeploy_processor_version_rest_interceptors(null_interceptor): +def test_enable_processor_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8888,16 +11169,14 @@ def test_undeploy_processor_version_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "post_undeploy_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "pre_undeploy_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.UndeployProcessorVersionRequest.pb( - document_processor_service.UndeployProcessorVersionRequest() + pb_message = document_processor_service.EnableProcessorRequest.pb( + document_processor_service.EnableProcessorRequest() ) transcode.return_value = { "method": "post", @@ -8913,7 +11192,7 @@ def test_undeploy_processor_version_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = document_processor_service.UndeployProcessorVersionRequest() + request = document_processor_service.EnableProcessorRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8921,7 +11200,7 @@ def test_undeploy_processor_version_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.undeploy_processor_version( + client.enable_processor( request, metadata=[ ("key", "val"), @@ -8933,9 +11212,9 @@ def test_undeploy_processor_version_rest_interceptors(null_interceptor): post.assert_called_once() -def test_undeploy_processor_version_rest_bad_request( +def test_enable_processor_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.UndeployProcessorVersionRequest, + request_type=document_processor_service.EnableProcessorRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8943,9 +11222,7 @@ def test_undeploy_processor_version_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8957,67 +11234,10 @@ def test_undeploy_processor_version_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.undeploy_processor_version(request) - - -def test_undeploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.undeploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" - % client.transport._host, - args[1], - ) - - -def test_undeploy_processor_version_rest_flattened_error(transport: str = "rest"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name="name_value", - ) + client.enable_processor(request) -def test_undeploy_processor_version_rest_error(): +def test_enable_processor_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9026,71 +11246,45 @@ def test_undeploy_processor_version_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.CreateProcessorRequest, + document_processor_service.DisableProcessorRequest, dict, ], ) -def test_create_processor_rest(request_type): +def test_disable_processor_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["processor"] = { - "name": "name_value", - "type_": "type__value", - "display_name": "display_name_value", - "state": 1, - "default_processor_version": "default_processor_version_value", - "process_endpoint": "process_endpoint_value", - "create_time": {"seconds": 751, "nanos": 543}, - "kms_key_name": "kms_key_name_value", - } + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor( - name="name_value", - type_="type__value", - display_name="display_name_value", - state=gcd_processor.Processor.State.ENABLED, - default_processor_version="default_processor_version_value", - process_endpoint="process_endpoint_value", - kms_key_name="kms_key_name_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_processor(request) + response = client.disable_processor(request) # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == "name_value" - assert response.type_ == "type__value" - assert response.display_name == "display_name_value" - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == "default_processor_version_value" - assert response.process_endpoint == "process_endpoint_value" - assert response.kms_key_name == "kms_key_name_value" + assert response.operation.name == "operations/spam" -def test_create_processor_rest_required_fields( - request_type=document_processor_service.CreateProcessorRequest, +def test_disable_processor_rest_required_fields( + request_type=document_processor_service.DisableProcessorRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9105,21 +11299,21 @@ def test_create_processor_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_processor._get_unset_required_fields(jsonified_request) + ).disable_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_processor._get_unset_required_fields(jsonified_request) + ).disable_processor._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9128,7 +11322,7 @@ def test_create_processor_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -9148,39 +11342,29 @@ def test_create_processor_rest_required_fields( response_value = Response() response_value.status_code = 200 - - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_processor(request) + response = client.disable_processor(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_processor_rest_unset_required_fields(): +def test_disable_processor_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_processor._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "processor", - ) - ) - ) + unset_fields = transport.disable_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_processor_rest_interceptors(null_interceptor): +def test_disable_processor_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9193,14 +11377,16 @@ def test_create_processor_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_create_processor" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor" + transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.CreateProcessorRequest.pb( - document_processor_service.CreateProcessorRequest() + pb_message = document_processor_service.DisableProcessorRequest.pb( + document_processor_service.DisableProcessorRequest() ) transcode.return_value = { "method": "post", @@ -9212,19 +11398,19 @@ def test_create_processor_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gcd_processor.Processor.to_json( - gcd_processor.Processor() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = document_processor_service.CreateProcessorRequest() + request = document_processor_service.DisableProcessorRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gcd_processor.Processor() + post.return_value = operations_pb2.Operation() - client.create_processor( + client.disable_processor( request, metadata=[ ("key", "val"), @@ -9236,9 +11422,9 @@ def test_create_processor_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_processor_rest_bad_request( +def test_disable_processor_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.CreateProcessorRequest, + request_type=document_processor_service.DisableProcessorRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9246,17 +11432,7 @@ def test_create_processor_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["processor"] = { - "name": "name_value", - "type_": "type__value", - "display_name": "display_name_value", - "state": 1, - "default_processor_version": "default_processor_version_value", - "process_endpoint": "process_endpoint_value", - "create_time": {"seconds": 751, "nanos": 543}, - "kms_key_name": "kms_key_name_value", - } + request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9268,67 +11444,10 @@ def test_create_processor_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_processor(request) - - -def test_create_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - processor=gcd_processor.Processor(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, - args[1], - ) - - -def test_create_processor_rest_flattened_error(transport: str = "rest"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent="parent_value", - processor=gcd_processor.Processor(name="name_value"), - ) + client.disable_processor(request) -def test_create_processor_rest_error(): +def test_disable_processor_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9337,18 +11456,20 @@ def test_create_processor_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.DeleteProcessorRequest, + document_processor_service.SetDefaultProcessorVersionRequest, dict, ], ) -def test_delete_processor_rest(request_type): +def test_set_default_processor_version_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "processor": "projects/sample1/locations/sample2/processors/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9363,19 +11484,20 @@ def test_delete_processor_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_processor(request) + response = client.set_default_processor_version(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_processor_rest_required_fields( - request_type=document_processor_service.DeleteProcessorRequest, +def test_set_default_processor_version_rest_required_fields( + request_type=document_processor_service.SetDefaultProcessorVersionRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["processor"] = "" + request_init["default_processor_version"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9390,21 +11512,27 @@ def test_delete_processor_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_processor._get_unset_required_fields(jsonified_request) + ).set_default_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["processor"] = "processor_value" + jsonified_request["defaultProcessorVersion"] = "default_processor_version_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_processor._get_unset_required_fields(jsonified_request) + ).set_default_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "processor" in jsonified_request + assert jsonified_request["processor"] == "processor_value" + assert "defaultProcessorVersion" in jsonified_request + assert ( + jsonified_request["defaultProcessorVersion"] + == "default_processor_version_value" + ) client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9425,9 +11553,10 @@ def test_delete_processor_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9437,24 +11566,34 @@ def test_delete_processor_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_processor(request) + response = client.set_default_processor_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_processor_rest_unset_required_fields(): +def test_set_default_processor_version_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.set_default_processor_version._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "processor", + "defaultProcessorVersion", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_rest_interceptors(null_interceptor): +def test_set_default_processor_version_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9469,14 +11608,16 @@ def test_delete_processor_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor" + transports.DocumentProcessorServiceRestInterceptor, + "post_set_default_processor_version", ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor" + transports.DocumentProcessorServiceRestInterceptor, + "pre_set_default_processor_version", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorRequest.pb( - document_processor_service.DeleteProcessorRequest() + pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb( + document_processor_service.SetDefaultProcessorVersionRequest() ) transcode.return_value = { "method": "post", @@ -9492,7 +11633,7 @@ def test_delete_processor_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = document_processor_service.DeleteProcessorRequest() + request = document_processor_service.SetDefaultProcessorVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9500,7 +11641,7 @@ def test_delete_processor_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_processor( + client.set_default_processor_version( request, metadata=[ ("key", "val"), @@ -9512,88 +11653,34 @@ def test_delete_processor_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_processor_rest_bad_request( +def test_set_default_processor_version_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.DeleteProcessorRequest, + request_type=document_processor_service.SetDefaultProcessorVersionRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor(request) - - -def test_delete_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/processors/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, - args[1], - ) - - -def test_delete_processor_rest_flattened_error(transport: str = "rest"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name="name_value", - ) + # send a request that will satisfy transcoding + request_init = { + "processor": "projects/sample1/locations/sample2/processors/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_default_processor_version(request) -def test_delete_processor_rest_error(): + +def test_set_default_processor_version_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9602,18 +11689,20 @@ def test_delete_processor_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.EnableProcessorRequest, + document_processor_service.ReviewDocumentRequest, dict, ], ) -def test_enable_processor_rest(request_type): +def test_review_document_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "human_review_config": "projects/sample1/locations/sample2/processors/sample3/humanReviewConfig" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9628,19 +11717,19 @@ def test_enable_processor_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.enable_processor(request) + response = client.review_document(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_enable_processor_rest_required_fields( - request_type=document_processor_service.EnableProcessorRequest, +def test_review_document_rest_required_fields( + request_type=document_processor_service.ReviewDocumentRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["human_review_config"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9655,21 +11744,21 @@ def test_enable_processor_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).enable_processor._get_unset_required_fields(jsonified_request) + ).review_document._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["humanReviewConfig"] = "human_review_config_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).enable_processor._get_unset_required_fields(jsonified_request) + ).review_document._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "humanReviewConfig" in jsonified_request + assert jsonified_request["humanReviewConfig"] == "human_review_config_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9703,24 +11792,24 @@ def test_enable_processor_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.enable_processor(request) + response = client.review_document(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_enable_processor_rest_unset_required_fields(): +def test_review_document_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.enable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.review_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("humanReviewConfig",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_processor_rest_interceptors(null_interceptor): +def test_review_document_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9735,14 +11824,14 @@ def test_enable_processor_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor" + transports.DocumentProcessorServiceRestInterceptor, "post_review_document" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor" + transports.DocumentProcessorServiceRestInterceptor, "pre_review_document" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.EnableProcessorRequest.pb( - document_processor_service.EnableProcessorRequest() + pb_message = document_processor_service.ReviewDocumentRequest.pb( + document_processor_service.ReviewDocumentRequest() ) transcode.return_value = { "method": "post", @@ -9758,7 +11847,7 @@ def test_enable_processor_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = document_processor_service.EnableProcessorRequest() + request = document_processor_service.ReviewDocumentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9766,7 +11855,7 @@ def test_enable_processor_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.enable_processor( + client.review_document( request, metadata=[ ("key", "val"), @@ -9778,9 +11867,9 @@ def test_enable_processor_rest_interceptors(null_interceptor): post.assert_called_once() -def test_enable_processor_rest_bad_request( +def test_review_document_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.EnableProcessorRequest, + request_type=document_processor_service.ReviewDocumentRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9788,7 +11877,9 @@ def test_enable_processor_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "human_review_config": "projects/sample1/locations/sample2/processors/sample3/humanReviewConfig" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9800,10 +11891,67 @@ def test_enable_processor_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.enable_processor(request) + client.review_document(request) -def test_enable_processor_rest_error(): +def test_review_document_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "human_review_config": "projects/sample1/locations/sample2/processors/sample3/humanReviewConfig" + } + + # get truthy value for each flattened field + mock_args = dict( + human_review_config="human_review_config_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.review_document(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" + % client.transport._host, + args[1], + ) + + +def test_review_document_rest_flattened_error(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.review_document( + document_processor_service.ReviewDocumentRequest(), + human_review_config="human_review_config_value", + ) + + +def test_review_document_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9812,18 +11960,20 @@ def test_enable_processor_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.DisableProcessorRequest, + document_processor_service.EvaluateProcessorVersionRequest, dict, ], ) -def test_disable_processor_rest(request_type): +def test_evaluate_processor_version_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "processor_version": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9838,19 +11988,19 @@ def test_disable_processor_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.disable_processor(request) + response = client.evaluate_processor_version(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_disable_processor_rest_required_fields( - request_type=document_processor_service.DisableProcessorRequest, +def test_evaluate_processor_version_rest_required_fields( + request_type=document_processor_service.EvaluateProcessorVersionRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["processor_version"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9865,21 +12015,21 @@ def test_disable_processor_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).disable_processor._get_unset_required_fields(jsonified_request) + ).evaluate_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["processorVersion"] = "processor_version_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).disable_processor._get_unset_required_fields(jsonified_request) + ).evaluate_processor_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "processorVersion" in jsonified_request + assert jsonified_request["processorVersion"] == "processor_version_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9913,24 +12063,24 @@ def test_disable_processor_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.disable_processor(request) + response = client.evaluate_processor_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_disable_processor_rest_unset_required_fields(): +def test_evaluate_processor_version_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.disable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.evaluate_processor_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("processorVersion",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_processor_rest_interceptors(null_interceptor): +def test_evaluate_processor_version_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9945,14 +12095,16 @@ def test_disable_processor_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor" + transports.DocumentProcessorServiceRestInterceptor, + "post_evaluate_processor_version", ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor" + transports.DocumentProcessorServiceRestInterceptor, + "pre_evaluate_processor_version", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.DisableProcessorRequest.pb( - document_processor_service.DisableProcessorRequest() + pb_message = document_processor_service.EvaluateProcessorVersionRequest.pb( + document_processor_service.EvaluateProcessorVersionRequest() ) transcode.return_value = { "method": "post", @@ -9968,7 +12120,7 @@ def test_disable_processor_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = document_processor_service.DisableProcessorRequest() + request = document_processor_service.EvaluateProcessorVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9976,7 +12128,7 @@ def test_disable_processor_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.disable_processor( + client.evaluate_processor_version( request, metadata=[ ("key", "val"), @@ -9988,9 +12140,9 @@ def test_disable_processor_rest_interceptors(null_interceptor): post.assert_called_once() -def test_disable_processor_rest_bad_request( +def test_evaluate_processor_version_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.DisableProcessorRequest, + request_type=document_processor_service.EvaluateProcessorVersionRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9998,7 +12150,9 @@ def test_disable_processor_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/processors/sample3"} + request_init = { + "processor_version": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10010,10 +12164,67 @@ def test_disable_processor_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.disable_processor(request) + client.evaluate_processor_version(request) -def test_disable_processor_rest_error(): +def test_evaluate_processor_version_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "processor_version": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + processor_version="processor_version_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.evaluate_processor_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion" + % client.transport._host, + args[1], + ) + + +def test_evaluate_processor_version_rest_flattened_error(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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", + ) + + +def test_evaluate_processor_version_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10022,11 +12233,11 @@ def test_disable_processor_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, + document_processor_service.GetEvaluationRequest, dict, ], ) -def test_set_default_processor_version_rest(request_type): +def test_get_evaluation_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10034,36 +12245,43 @@ def test_set_default_processor_version_rest(request_type): # send a request that will satisfy transcoding request_init = { - "processor": "projects/sample1/locations/sample2/processors/sample3" + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = evaluation.Evaluation( + name="name_value", + kms_key_name="kms_key_name_value", + kms_key_version_name="kms_key_version_name_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_default_processor_version(request) + response = client.get_evaluation(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + 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_set_default_processor_version_rest_required_fields( - request_type=document_processor_service.SetDefaultProcessorVersionRequest, +def test_get_evaluation_rest_required_fields( + request_type=document_processor_service.GetEvaluationRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["processor"] = "" - request_init["default_processor_version"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10078,27 +12296,21 @@ def test_set_default_processor_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_default_processor_version._get_unset_required_fields(jsonified_request) + ).get_evaluation._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["processor"] = "processor_value" - jsonified_request["defaultProcessorVersion"] = "default_processor_version_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_default_processor_version._get_unset_required_fields(jsonified_request) + ).get_evaluation._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "processor" in jsonified_request - assert jsonified_request["processor"] == "processor_value" - assert "defaultProcessorVersion" in jsonified_request - assert ( - jsonified_request["defaultProcessorVersion"] - == "default_processor_version_value" - ) + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10107,7 +12319,7 @@ def test_set_default_processor_version_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = evaluation.Evaluation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -10119,47 +12331,38 @@ def test_set_default_processor_version_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_default_processor_version(request) + response = client.get_evaluation(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_set_default_processor_version_rest_unset_required_fields(): +def test_get_evaluation_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.set_default_processor_version._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "processor", - "defaultProcessorVersion", - ) - ) - ) + unset_fields = transport.get_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_processor_version_rest_interceptors(null_interceptor): +def test_get_evaluation_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10172,18 +12375,14 @@ def test_set_default_processor_version_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "post_set_default_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "post_get_evaluation" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, - "pre_set_default_processor_version", + transports.DocumentProcessorServiceRestInterceptor, "pre_get_evaluation" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb( - document_processor_service.SetDefaultProcessorVersionRequest() + pb_message = document_processor_service.GetEvaluationRequest.pb( + document_processor_service.GetEvaluationRequest() ) transcode.return_value = { "method": "post", @@ -10195,19 +12394,19 @@ def test_set_default_processor_version_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = evaluation.Evaluation.to_json( + evaluation.Evaluation() ) - request = document_processor_service.SetDefaultProcessorVersionRequest() + request = document_processor_service.GetEvaluationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = evaluation.Evaluation() - client.set_default_processor_version( + client.get_evaluation( request, metadata=[ ("key", "val"), @@ -10219,9 +12418,9 @@ def test_set_default_processor_version_rest_interceptors(null_interceptor): post.assert_called_once() -def test_set_default_processor_version_rest_bad_request( +def test_get_evaluation_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.SetDefaultProcessorVersionRequest, + request_type=document_processor_service.GetEvaluationRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10230,7 +12429,7 @@ def test_set_default_processor_version_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "processor": "projects/sample1/locations/sample2/processors/sample3" + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5" } request = request_type(**request_init) @@ -10243,10 +12442,68 @@ def test_set_default_processor_version_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.set_default_processor_version(request) + client.get_evaluation(request) -def test_set_default_processor_version_rest_error(): +def test_get_evaluation_rest_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_rest_flattened_error(transport: str = "rest"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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", + ) + + +def test_get_evaluation_rest_error(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10255,11 +12512,11 @@ def test_set_default_processor_version_rest_error(): @pytest.mark.parametrize( "request_type", [ - document_processor_service.ReviewDocumentRequest, + document_processor_service.ListEvaluationsRequest, dict, ], ) -def test_review_document_rest(request_type): +def test_list_evaluations_rest(request_type): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10267,35 +12524,41 @@ def test_review_document_rest(request_type): # send a request that will satisfy transcoding request_init = { - "human_review_config": "projects/sample1/locations/sample2/processors/sample3/humanReviewConfig" + "parent": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = document_processor_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = document_processor_service.ListEvaluationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.review_document(request) + response = client.list_evaluations(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" -def test_review_document_rest_required_fields( - request_type=document_processor_service.ReviewDocumentRequest, +def test_list_evaluations_rest_required_fields( + request_type=document_processor_service.ListEvaluationsRequest, ): transport_class = transports.DocumentProcessorServiceRestTransport request_init = {} - request_init["human_review_config"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10310,21 +12573,28 @@ def test_review_document_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).review_document._get_unset_required_fields(jsonified_request) + ).list_evaluations._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["humanReviewConfig"] = "human_review_config_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).review_document._get_unset_required_fields(jsonified_request) + ).list_evaluations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "humanReviewConfig" in jsonified_request - assert jsonified_request["humanReviewConfig"] == "human_review_config_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10333,7 +12603,7 @@ def test_review_document_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = document_processor_service.ListEvaluationsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -10345,37 +12615,48 @@ def test_review_document_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = document_processor_service.ListEvaluationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.review_document(request) + response = client.list_evaluations(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_review_document_rest_unset_required_fields(): +def test_list_evaluations_rest_unset_required_fields(): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.review_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("humanReviewConfig",))) + unset_fields = transport.list_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_review_document_rest_interceptors(null_interceptor): +def test_list_evaluations_rest_interceptors(null_interceptor): transport = transports.DocumentProcessorServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10388,16 +12669,14 @@ def test_review_document_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "post_review_document" + transports.DocumentProcessorServiceRestInterceptor, "post_list_evaluations" ) as post, mock.patch.object( - transports.DocumentProcessorServiceRestInterceptor, "pre_review_document" + transports.DocumentProcessorServiceRestInterceptor, "pre_list_evaluations" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = document_processor_service.ReviewDocumentRequest.pb( - document_processor_service.ReviewDocumentRequest() + pb_message = document_processor_service.ListEvaluationsRequest.pb( + document_processor_service.ListEvaluationsRequest() ) transcode.return_value = { "method": "post", @@ -10409,19 +12688,21 @@ def test_review_document_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = ( + document_processor_service.ListEvaluationsResponse.to_json( + document_processor_service.ListEvaluationsResponse() + ) ) - request = document_processor_service.ReviewDocumentRequest() + request = document_processor_service.ListEvaluationsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = document_processor_service.ListEvaluationsResponse() - client.review_document( + client.list_evaluations( request, metadata=[ ("key", "val"), @@ -10433,9 +12714,9 @@ def test_review_document_rest_interceptors(null_interceptor): post.assert_called_once() -def test_review_document_rest_bad_request( +def test_list_evaluations_rest_bad_request( transport: str = "rest", - request_type=document_processor_service.ReviewDocumentRequest, + request_type=document_processor_service.ListEvaluationsRequest, ): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10444,7 +12725,7 @@ def test_review_document_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "human_review_config": "projects/sample1/locations/sample2/processors/sample3/humanReviewConfig" + "parent": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" } request = request_type(**request_init) @@ -10457,10 +12738,10 @@ def test_review_document_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.review_document(request) + client.list_evaluations(request) -def test_review_document_rest_flattened(): +def test_list_evaluations_rest_flattened(): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10469,40 +12750,43 @@ def test_review_document_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = document_processor_service.ListEvaluationsResponse() # get arguments that satisfy an http rule for this method sample_request = { - "human_review_config": "projects/sample1/locations/sample2/processors/sample3/humanReviewConfig" + "parent": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" } # get truthy value for each flattened field mock_args = dict( - human_review_config="human_review_config_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = document_processor_service.ListEvaluationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.review_document(**mock_args) + client.list_evaluations(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" + "%s/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations" % client.transport._host, args[1], ) -def test_review_document_rest_flattened_error(transport: str = "rest"): +def test_list_evaluations_rest_flattened_error(transport: str = "rest"): client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10511,17 +12795,77 @@ def test_review_document_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config="human_review_config_value", + client.list_evaluations( + document_processor_service.ListEvaluationsRequest(), + parent="parent_value", ) -def test_review_document_rest_error(): +def test_list_evaluations_rest_pager(transport: str = "rest"): client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + 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(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + document_processor_service.ListEvaluationsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4" + } + + pager = client.list_evaluations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + pages = list(client.list_evaluations(request=sample_request).pages) + 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. @@ -10669,6 +13013,7 @@ def test_document_processor_service_base_transport(): "get_processor_type", "list_processors", "get_processor", + "train_processor_version", "get_processor_version", "list_processor_versions", "delete_processor_version", @@ -10680,6 +13025,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", @@ -10990,6 +13338,9 @@ def test_document_processor_service_client_transport_session_collision(transport session1 = client1.transport.get_processor._session session2 = client2.transport.get_processor._session assert session1 != session2 + session1 = client1.transport.train_processor_version._session + session2 = client2.transport.train_processor_version._session + assert session1 != session2 session1 = client1.transport.get_processor_version._session session2 = client2.transport.get_processor_version._session assert session1 != session2 @@ -11023,6 +13374,15 @@ def test_document_processor_service_client_transport_session_collision(transport session1 = client1.transport.review_document._session session2 = client2.transport.review_document._session assert session1 != session2 + session1 = client1.transport.evaluate_processor_version._session + session2 = client2.transport.evaluate_processor_version._session + assert session1 != session2 + session1 = client1.transport.get_evaluation._session + session2 = client2.transport.get_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_evaluations._session + session2 = client2.transport.list_evaluations._session + assert session1 != session2 def test_document_processor_service_grpc_transport_channel(): @@ -11185,10 +13545,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, @@ -11202,9 +13596,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) @@ -11214,9 +13608,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, @@ -11228,9 +13622,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) @@ -11240,9 +13634,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, @@ -11256,9 +13650,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) @@ -11268,10 +13662,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, @@ -11286,10 +13680,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) @@ -11299,7 +13693,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, ) @@ -11309,7 +13703,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) @@ -11319,7 +13713,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -11329,7 +13723,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "octopus", } path = DocumentProcessorServiceClient.common_folder_path(**expected) @@ -11339,7 +13733,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -11349,7 +13743,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "nudibranch", } path = DocumentProcessorServiceClient.common_organization_path(**expected) @@ -11359,7 +13753,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -11369,7 +13763,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "mussel", } path = DocumentProcessorServiceClient.common_project_path(**expected) @@ -11379,8 +13773,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, @@ -11391,8 +13785,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)