From 04ce67eae3e55da1e6e32e3a9ae786452f70f472 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 9 Nov 2022 15:25:27 +0000 Subject: [PATCH] feat: added font_family to document.proto feat: added ImageQualityScores message to document.proto feat: added PropertyMetadata and EntityTypeMetadata to document_schema.proto PiperOrigin-RevId: 486975621 Source-Link: https://github.com/googleapis/googleapis/commit/398c9f9fccf4dea8d12e0b5a90ed671dec2ee387 Source-Link: https://github.com/googleapis/googleapis-gen/commit/7cd1f5f4e435777cb824af268dc8d37134613e6a Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiN2NkMWY1ZjRlNDM1Nzc3Y2I4MjRhZjI2OGRjOGQzNzEzNDYxM2U2YSJ9 --- owl-bot-staging/v1/.coveragerc | 17 + 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 | 7 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/documentai/__init__.py | 137 + .../google/cloud/documentai/gapic_version.py | 16 + .../v1/google/cloud/documentai/py.typed | 2 + .../v1/google/cloud/documentai_v1/__init__.py | 138 + .../cloud/documentai_v1/gapic_metadata.json | 193 + .../v1/google/cloud/documentai_v1/py.typed | 2 + .../cloud/documentai_v1/services/__init__.py | 15 + .../document_processor_service/__init__.py | 22 + .../async_client.py | 2414 +++++++ .../document_processor_service/client.py | 2619 +++++++ .../document_processor_service/pagers.py | 383 + .../transports/__init__.py | 33 + .../transports/base.py | 453 ++ .../transports/grpc.py | 810 +++ .../transports/grpc_asyncio.py | 809 +++ .../cloud/documentai_v1/types/__init__.py | 146 + .../cloud/documentai_v1/types/barcode.py | 83 + .../cloud/documentai_v1/types/document.py | 1609 +++++ .../cloud/documentai_v1/types/document_io.py | 191 + .../types/document_processor_service.py | 985 +++ .../documentai_v1/types/document_schema.py | 224 + .../cloud/documentai_v1/types/geometry.py | 97 + .../documentai_v1/types/operation_metadata.py | 79 + .../cloud/documentai_v1/types/processor.py | 217 + .../documentai_v1/types/processor_type.py | 97 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 179 + ...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 + ...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 + .../snippet_metadata_documentai_v1.json | 2735 +++++++ .../scripts/fixup_documentai_v1_keywords.py | 192 + 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.7.txt | 12 + .../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 | 6262 ++++++++++++++++ owl-bot-staging/v1beta2/.coveragerc | 17 + 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 | 7 + 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 + .../google/cloud/documentai_v1beta2/py.typed | 2 + .../documentai_v1beta2/services/__init__.py | 15 + .../__init__.py | 22 + .../async_client.py | 432 ++ .../document_understanding_service/client.py | 611 ++ .../transports/__init__.py | 33 + .../transports/base.py | 190 + .../transports/grpc.py | 313 + .../transports/grpc_asyncio.py | 312 + .../documentai_v1beta2/types/__init__.py | 64 + .../documentai_v1beta2/types/document.py | 1015 +++ .../types/document_understanding.py | 571 ++ .../documentai_v1beta2/types/geometry.py | 95 + owl-bot-staging/v1beta2/mypy.ini | 3 + owl-bot-staging/v1beta2/noxfile.py | 179 + ...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 + .../snippet_metadata_documentai_v1beta2.json | 328 + .../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.7.txt | 11 + .../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 | 17 + 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 | 7 + owl-bot-staging/v1beta3/docs/index.rst | 7 + .../google/cloud/documentai/__init__.py | 137 + .../google/cloud/documentai/gapic_version.py | 16 + .../v1beta3/google/cloud/documentai/py.typed | 2 + .../cloud/documentai_v1beta3/__init__.py | 138 + .../documentai_v1beta3/gapic_metadata.json | 193 + .../google/cloud/documentai_v1beta3/py.typed | 2 + .../documentai_v1beta3/services/__init__.py | 15 + .../document_processor_service/__init__.py | 22 + .../async_client.py | 2415 +++++++ .../document_processor_service/client.py | 2620 +++++++ .../document_processor_service/pagers.py | 383 + .../transports/__init__.py | 33 + .../transports/base.py | 453 ++ .../transports/grpc.py | 810 +++ .../transports/grpc_asyncio.py | 809 +++ .../documentai_v1beta3/types/__init__.py | 146 + .../cloud/documentai_v1beta3/types/barcode.py | 67 + .../documentai_v1beta3/types/document.py | 1542 ++++ .../documentai_v1beta3/types/document_io.py | 178 + .../types/document_processor_service.py | 1109 +++ .../types/document_schema.py | 224 + .../documentai_v1beta3/types/geometry.py | 97 + .../types/operation_metadata.py | 79 + .../documentai_v1beta3/types/processor.py | 207 + .../types/processor_type.py | 96 + owl-bot-staging/v1beta3/mypy.ini | 3 + owl-bot-staging/v1beta3/noxfile.py | 179 + ...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 + ...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 + .../snippet_metadata_documentai_v1beta3.json | 2735 +++++++ .../fixup_documentai_v1beta3_keywords.py | 192 + 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.7.txt | 11 + .../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 | 6266 +++++++++++++++++ 212 files changed, 54491 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/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/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/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_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_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_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_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_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_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.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/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_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.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/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/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/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_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_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_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_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_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_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.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..ef619357 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/documentai/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound 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..68ac7119 --- /dev/null +++ b/owl-bot-staging/v1/docs/documentai_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Documentai v1 API +======================================== + +.. automodule:: google.cloud.documentai_v1.types + :members: + :undoc-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..345c4ea4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai/__init__.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 FetchProcessorTypesRequest +from google.cloud.documentai_v1.types.document_processor_service import FetchProcessorTypesResponse +from google.cloud.documentai_v1.types.document_processor_service import GetProcessorRequest +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 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 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.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', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + '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..35859c3f --- /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" 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..756936a4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/__init__.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .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 FetchProcessorTypesRequest +from .types.document_processor_service import FetchProcessorTypesResponse +from .types.document_processor_service import GetProcessorRequest +from .types.document_processor_service import GetProcessorVersionRequest +from .types.document_processor_service import HumanReviewStatus +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 UndeployProcessorVersionMetadata +from .types.document_processor_service import UndeployProcessorVersionRequest +from .types.document_processor_service import UndeployProcessorVersionResponse +from .types.document_schema import DocumentSchema +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', +'FetchProcessorTypesRequest', +'FetchProcessorTypesResponse', +'GcsDocument', +'GcsDocuments', +'GcsPrefix', +'GetProcessorRequest', +'GetProcessorVersionRequest', +'HumanReviewStatus', +'ListProcessorTypesRequest', +'ListProcessorTypesResponse', +'ListProcessorVersionsRequest', +'ListProcessorVersionsResponse', +'ListProcessorsRequest', +'ListProcessorsResponse', +'NormalizedVertex', +'ProcessRequest', +'ProcessResponse', +'Processor', +'ProcessorType', +'ProcessorVersion', +'RawDocument', +'ReviewDocumentOperationMetadata', +'ReviewDocumentRequest', +'ReviewDocumentResponse', +'SetDefaultProcessorVersionMetadata', +'SetDefaultProcessorVersionRequest', +'SetDefaultProcessorVersionResponse', +'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..8436c789 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/gapic_metadata.json @@ -0,0 +1,193 @@ + { + "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" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "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" + ] + }, + "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" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "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" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_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..c247de01 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py @@ -0,0 +1,2414 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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_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 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 + + 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 variabel 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: ga_credentials.Credentials = None, + transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", + client_options: 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: Union[document_processor_service.ProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.BatchProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.FetchProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.ListProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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 list_processors(self, + request: Union[document_processor_service.ListProcessorsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.GetProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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 get_processor_version(self, + request: Union[document_processor_service.GetProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.ListProcessorVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DeleteProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.UndeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.CreateProcessorRequest, dict] = None, + *, + parent: str = None, + processor: gcd_processor.Processor = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DeleteProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.EnableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DisableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.SetDefaultProcessorVersionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.ReviewDocumentRequest, dict] = None, + *, + human_review_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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 list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.CancelOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.GetLocationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-documentai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..1da1e629 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/client.py @@ -0,0 +1,2619 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Optional, Sequence, Tuple, Type, Union, cast +import pkg_resources + +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_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 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 + + +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 + + def get_transport_class(cls, + label: 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 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 variabel 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: Union[str, DocumentProcessorServiceTransport, None] = 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: Union[document_processor_service.ProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.BatchProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.FetchProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.ListProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 list_processors(self, + request: Union[document_processor_service.ListProcessorsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.GetProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 get_processor_version(self, + request: Union[document_processor_service.GetProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.ListProcessorVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DeleteProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.UndeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.CreateProcessorRequest, dict] = None, + *, + parent: str = None, + processor: gcd_processor.Processor = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DeleteProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.EnableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DisableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.SetDefaultProcessorVersionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.ReviewDocumentRequest, dict] = None, + *, + human_review_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 __enter__(self): + 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: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.CancelOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.GetLocationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-documentai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..65e36fc3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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) 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..d64bf9dd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_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 DocumentProcessorServiceTransport +from .grpc import DocumentProcessorServiceGrpcTransport +from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] +_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport + +__all__ = ( + 'DocumentProcessorServiceTransport', + 'DocumentProcessorServiceGrpcTransport', + 'DocumentProcessorServiceGrpcAsyncIOTransport', +) 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..39e0c056 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import pkg_resources + +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 processor +from google.cloud.documentai_v1.types import processor as gcd_processor +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-documentai', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +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: 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.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.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, + ), + } + + 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 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 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 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..1c5869db --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py @@ -0,0 +1,810 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 processor +from google.cloud.documentai_v1.types import processor as gcd_processor +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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: ga_credentials.Credentials = None, + credentials_file: 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 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 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'] + + 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..ffc97bd0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py @@ -0,0 +1,809 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 processor +from google.cloud.documentai_v1.types import processor as gcd_processor +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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=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 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 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'] + + 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/types/__init__.py b/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py new file mode 100644 index 00000000..4eb71575 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/__init__.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + FetchProcessorTypesRequest, + FetchProcessorTypesResponse, + GetProcessorRequest, + GetProcessorVersionRequest, + HumanReviewStatus, + ListProcessorsRequest, + ListProcessorsResponse, + ListProcessorTypesRequest, + ListProcessorTypesResponse, + ListProcessorVersionsRequest, + ListProcessorVersionsResponse, + ProcessRequest, + ProcessResponse, + ReviewDocumentOperationMetadata, + ReviewDocumentRequest, + ReviewDocumentResponse, + SetDefaultProcessorVersionMetadata, + SetDefaultProcessorVersionRequest, + SetDefaultProcessorVersionResponse, + UndeployProcessorVersionMetadata, + UndeployProcessorVersionRequest, + UndeployProcessorVersionResponse, +) +from .document_schema import ( + DocumentSchema, +) +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', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + '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..901d5a5e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/barcode.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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_ = proto.Field( + proto.STRING, + number=1, + ) + value_format = proto.Field( + proto.STRING, + number=2, + ) + raw_value = 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..abcbcba3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document.py @@ -0,0 +1,1609 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[google.cloud.documentai_v1.types.Document.Style]): + Placeholder. Styles for the + [Document.text][google.cloud.documentai.v1.Document.text]. + pages (Sequence[google.cloud.documentai_v1.types.Document.Page]): + Visual page layout for the + [Document][google.cloud.documentai.v1.Document]. + entities (Sequence[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 (Sequence[google.cloud.documentai_v1.types.Document.EntityRelation]): + Placeholder. Relationship among + [Document.entities][google.cloud.documentai.v1.Document.entities]. + text_changes (Sequence[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 (Sequence[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 = proto.Field( + proto.INT64, + number=1, + ) + shard_count = proto.Field( + proto.INT64, + number=2, + ) + text_offset = 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 = proto.Field( + proto.FLOAT, + number=1, + ) + unit = proto.Field( + proto.STRING, + number=2, + ) + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + color = proto.Field( + proto.MESSAGE, + number=2, + message=color_pb2.Color, + ) + background_color = proto.Field( + proto.MESSAGE, + number=3, + message=color_pb2.Color, + ) + font_weight = proto.Field( + proto.STRING, + number=4, + ) + text_style = proto.Field( + proto.STRING, + number=5, + ) + text_decoration = proto.Field( + proto.STRING, + number=6, + ) + font_size = proto.Field( + proto.MESSAGE, + number=7, + message='Document.Style.FontSize', + ) + font_family = 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 (Sequence[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 (Sequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + blocks (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.documentai_v1.types.Document.Page.Token]): + A list of visually detected tokens on the + page. + visual_elements (Sequence[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 (Sequence[google.cloud.documentai_v1.types.Document.Page.Table]): + A list of visually detected tables on the + page. + form_fields (Sequence[google.cloud.documentai_v1.types.Document.Page.FormField]): + A list of visually detected form fields on + the page. + symbols (Sequence[google.cloud.documentai_v1.types.Document.Page.Symbol]): + A list of visually detected symbols on the + page. + detected_barcodes (Sequence[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 = proto.Field( + proto.FLOAT, + number=1, + ) + height = proto.Field( + proto.FLOAT, + number=2, + ) + unit = 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 = proto.Field( + proto.BYTES, + number=1, + ) + mime_type = proto.Field( + proto.STRING, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + height = 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 = proto.Field( + proto.INT32, + number=1, + ) + cols = proto.Field( + proto.INT32, + number=2, + ) + type_ = proto.Field( + proto.INT32, + number=3, + ) + data = 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.""" + ORIENTATION_UNSPECIFIED = 0 + PAGE_UP = 1 + PAGE_RIGHT = 2 + PAGE_DOWN = 3 + PAGE_LEFT = 4 + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + bounding_poly = proto.Field( + proto.MESSAGE, + number=3, + message=geometry.BoundingPoly, + ) + 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 (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[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.""" + TYPE_UNSPECIFIED = 0 + SPACE = 1 + WIDE_SPACE = 2 + HYPHEN = 3 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Document.Page.Token.DetectedBreak.Type', + ) + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_break = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Token.DetectedBreak', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): + Header rows of the table. + body_rows (Sequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): + Body rows of the table. + detected_languages (Sequence[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 (Sequence[google.cloud.documentai_v1.types.Document.Page.Table.TableCell]): + Cells that make up this row. + """ + + cells = 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 (Sequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + row_span = proto.Field( + proto.INT32, + number=2, + ) + col_span = proto.Field( + proto.INT32, + number=3, + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + header_rows = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.Table.TableRow', + ) + body_rows = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.Table.TableRow', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): + A list of detected languages for name + together with confidence. + value_detected_languages (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + field_value = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Layout', + ) + name_detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + value_detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + value_type = proto.Field( + proto.STRING, + number=5, + ) + corrected_key_text = proto.Field( + proto.STRING, + number=6, + ) + corrected_value_text = proto.Field( + proto.STRING, + number=7, + ) + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + 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 = proto.Field( + proto.STRING, + number=1, + ) + confidence = 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 (Sequence[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_ = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + quality_score = proto.Field( + proto.FLOAT, + number=1, + ) + detected_defects = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.ImageQualityScores.DetectedDefect', + ) + + page_number = proto.Field( + proto.INT32, + number=1, + ) + image = proto.Field( + proto.MESSAGE, + number=13, + message='Document.Page.Image', + ) + transforms = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='Document.Page.Matrix', + ) + dimension = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Dimension', + ) + layout = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + blocks = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Document.Page.Block', + ) + paragraphs = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Document.Page.Paragraph', + ) + lines = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Document.Page.Line', + ) + tokens = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Document.Page.Token', + ) + visual_elements = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Document.Page.VisualElement', + ) + tables = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Page.Table', + ) + form_fields = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='Document.Page.FormField', + ) + symbols = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='Document.Page.Symbol', + ) + detected_barcodes = proto.RepeatedField( + proto.MESSAGE, + number=15, + message='Document.Page.DetectedBarcode', + ) + image_quality_scores = proto.Field( + proto.MESSAGE, + number=17, + message='Document.Page.ImageQualityScores', + ) + 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 (Sequence[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 int + 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 = proto.Field( + proto.MESSAGE, + number=2, + oneof='structured_value', + message=money_pb2.Money, + ) + date_value = proto.Field( + proto.MESSAGE, + number=3, + oneof='structured_value', + message=date_pb2.Date, + ) + datetime_value = proto.Field( + proto.MESSAGE, + number=4, + oneof='structured_value', + message=datetime_pb2.DateTime, + ) + address_value = proto.Field( + proto.MESSAGE, + number=5, + oneof='structured_value', + message=postal_address_pb2.PostalAddress, + ) + boolean_value = proto.Field( + proto.BOOL, + number=6, + oneof='structured_value', + ) + integer_value = proto.Field( + proto.INT32, + number=7, + oneof='structured_value', + ) + float_value = proto.Field( + proto.FLOAT, + number=8, + oneof='structured_value', + ) + text = proto.Field( + proto.STRING, + number=1, + ) + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + mention_text = proto.Field( + proto.STRING, + number=3, + ) + mention_id = proto.Field( + proto.STRING, + number=4, + ) + confidence = proto.Field( + proto.FLOAT, + number=5, + ) + page_anchor = proto.Field( + proto.MESSAGE, + number=6, + message='Document.PageAnchor', + ) + id = proto.Field( + proto.STRING, + number=7, + ) + normalized_value = proto.Field( + proto.MESSAGE, + number=9, + message='Document.Entity.NormalizedValue', + ) + properties = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Entity', + ) + provenance = proto.Field( + proto.MESSAGE, + number=11, + message='Document.Provenance', + ) + redacted = 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 = proto.Field( + proto.STRING, + number=1, + ) + object_id = proto.Field( + proto.STRING, + number=2, + ) + relation = 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 (Sequence[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 = proto.Field( + proto.INT64, + number=1, + ) + end_index = proto.Field( + proto.INT64, + number=2, + ) + + text_segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.TextAnchor.TextSegment', + ) + content = 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 (Sequence[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.""" + LAYOUT_TYPE_UNSPECIFIED = 0 + BLOCK = 1 + PARAGRAPH = 2 + LINE = 3 + TOKEN = 4 + VISUAL_ELEMENT = 5 + TABLE = 6 + FORM_FIELD = 7 + + page = proto.Field( + proto.INT64, + number=1, + ) + layout_type = proto.Field( + proto.ENUM, + number=2, + enum='Document.PageAnchor.PageRef.LayoutType', + ) + layout_id = proto.Field( + proto.STRING, + number=3, + ) + bounding_poly = proto.Field( + proto.MESSAGE, + number=4, + message=geometry.BoundingPoly, + ) + confidence = proto.Field( + proto.FLOAT, + number=5, + ) + + page_refs = 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 (Sequence[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. + """ + OPERATION_TYPE_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + 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 = proto.Field( + proto.INT32, + number=1, + ) + index = proto.Field( + proto.INT32, + number=3, + ) + id = proto.Field( + proto.INT32, + number=2, + ) + + revision = proto.Field( + proto.INT32, + number=1, + ) + id = proto.Field( + proto.INT32, + number=2, + ) + parents = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance.Parent', + ) + type_ = 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. Unique within the + context of the document. + parent (Sequence[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 (Sequence[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. + 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 = proto.Field( + proto.STRING, + number=1, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + + agent = proto.Field( + proto.STRING, + number=4, + oneof='source', + ) + processor = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + id = proto.Field( + proto.STRING, + number=1, + ) + parent = proto.RepeatedField( + proto.INT32, + number=2, + ) + parent_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + human_review = 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 (Sequence[google.cloud.documentai_v1.types.Document.Provenance]): + The history of this annotation. + """ + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + changed_text = proto.Field( + proto.STRING, + number=2, + ) + provenance = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + uri = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + content = proto.Field( + proto.BYTES, + number=2, + oneof='source', + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + text = proto.Field( + proto.STRING, + number=4, + ) + text_styles = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Style, + ) + pages = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Page, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Entity, + ) + entity_relations = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=EntityRelation, + ) + text_changes = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=TextChange, + ) + shard_info = proto.Field( + proto.MESSAGE, + number=9, + message=ShardInfo, + ) + error = proto.Field( + proto.MESSAGE, + number=10, + message=status_pb2.Status, + ) + revisions = 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..742c6fc6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_io.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 = proto.Field( + proto.BYTES, + number=1, + ) + mime_type = 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 = proto.Field( + proto.STRING, + number=1, + ) + mime_type = proto.Field( + proto.STRING, + number=2, + ) + + +class GcsDocuments(proto.Message): + r"""Specifies a set of documents on Cloud Storage. + + Attributes: + documents (Sequence[google.cloud.documentai_v1.types.GcsDocument]): + The list of documents. + """ + + documents = 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 = 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 = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsPrefix', + ) + gcs_documents = 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}``. + """ + + gcs_uri = proto.Field( + proto.STRING, + number=1, + ) + field_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + gcs_output_config = 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..0d753655 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_processor_service.py @@ -0,0 +1,985 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 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', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'DeleteProcessorVersionRequest', + 'DeleteProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'CreateProcessorRequest', + 'DeleteProcessorRequest', + 'DeleteProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EnableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'DisableProcessorMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'SetDefaultProcessorVersionMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'ReviewDocumentOperationMetadata', + }, +) + + +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 = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + raw_document = proto.Field( + proto.MESSAGE, + number=5, + oneof='source', + message=document_io.RawDocument, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + skip_human_review = proto.Field( + proto.BOOL, + number=3, + ) + field_mask = 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.""" + STATE_UNSPECIFIED = 0 + SKIPPED = 1 + VALIDATION_PASSED = 2 + IN_PROGRESS = 3 + ERROR = 4 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + human_review_operation = 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 = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + human_review_status = 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 = proto.Field( + proto.STRING, + number=1, + ) + input_documents = proto.Field( + proto.MESSAGE, + number=5, + message=document_io.BatchDocumentsInputConfig, + ) + document_output_config = proto.Field( + proto.MESSAGE, + number=6, + message=document_io.DocumentOutputConfig, + ) + skip_human_review = 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 (Sequence[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.""" + 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 = proto.Field( + proto.STRING, + number=1, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + output_gcs_destination = proto.Field( + proto.STRING, + number=3, + ) + human_review_status = proto.Field( + proto.MESSAGE, + number=5, + message='HumanReviewStatus', + ) + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + individual_process_statuses = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchProcessorTypesResponse(proto.Message): + r"""Response message for fetch processor types. + + Attributes: + processor_types (Sequence[google.cloud.documentai_v1.types.ProcessorType]): + The list of processor types. + """ + + processor_types = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListProcessorTypesResponse(proto.Message): + r"""Response message for list processor types. + + Attributes: + processor_types (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=processor_type.ProcessorType, + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListProcessorsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processors (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.Processor, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetProcessorRequest(proto.Message): + r"""Request message for get processor. + + Attributes: + name (str): + Required. The processor resource name. + """ + + name = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListProcessorVersionsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processor_versions (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.ProcessorVersion, + ) + next_page_token = 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 = 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 = 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 = 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 = 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 = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + 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 = 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 = 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 = 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 = 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 = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + default_processor_version = 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 = proto.Field( + proto.MESSAGE, + number=1, + message=operation_metadata.CommonOperationMetadata, + ) + + +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.""" + DEFAULT = 0 + URGENT = 1 + + inline_document = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + human_review_config = proto.Field( + proto.STRING, + number=1, + ) + enable_schema_validation = proto.Field( + proto.BOOL, + number=3, + ) + priority = proto.Field( + proto.ENUM, + number=5, + enum=Priority, + ) + document_schema = 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.""" + STATE_UNSPECIFIED = 0 + REJECTED = 1 + SUCCEEDED = 2 + + gcs_destination = proto.Field( + proto.STRING, + number=1, + ) + state = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + rejection_reason = 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 = proto.Field( + proto.MESSAGE, + number=5, + message=operation_metadata.CommonOperationMetadata, + ) + question_id = proto.Field( + proto.STRING, + number=6, + ) + + +__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..89dceca8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/document_schema.py @@ -0,0 +1,224 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[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-insensitive + - Maximum 64 characters. + - Must start with a letter. + - Allowed characters: ASCII letters ``[a-z0-9_-]``. (For + backward compatibility internal infrastructure and + tooling can handle any ascii character) + - The ``/`` is sometimes used to denote a property of a + type. For example ``line_item/amount``. This convention + is deprecated, but will still be honored for backward + compatibility. + base_types (Sequence[str]): + The entity type that this type is derived + from. For now, one and only one should be set. + properties (Sequence[google.cloud.documentai_v1.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 (Sequence[str]): + The individual values that this enum values + type can include. + """ + + values = 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. + Note: this represents the number of instances of an entity + types, not number of mentions of a given entity instance. + """ + OCCURRENCE_TYPE_UNSPECIFIED = 0 + OPTIONAL_ONCE = 1 + OPTIONAL_MULTIPLE = 2 + REQUIRED_ONCE = 3 + REQUIRED_MULTIPLE = 4 + + name = proto.Field( + proto.STRING, + number=1, + ) + value_type = proto.Field( + proto.STRING, + number=2, + ) + occurrence_type = proto.Field( + proto.ENUM, + number=3, + enum='DocumentSchema.EntityType.Property.OccurrenceType', + ) + + enum_values = proto.Field( + proto.MESSAGE, + number=14, + oneof='value_source', + message='DocumentSchema.EntityType.EnumValues', + ) + display_name = proto.Field( + proto.STRING, + number=13, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + base_types = proto.RepeatedField( + proto.STRING, + number=2, + ) + properties = 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 = proto.Field( + proto.BOOL, + number=1, + ) + document_allow_multiple_labels = proto.Field( + proto.BOOL, + number=2, + ) + prefixed_naming_on_properties = proto.Field( + proto.BOOL, + number=6, + ) + skip_naming_validation = proto.Field( + proto.BOOL, + number=7, + ) + + display_name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=EntityType, + ) + 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 new file mode 100644 index 00000000..688bef0c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/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. +# +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 = proto.Field( + proto.INT32, + number=1, + ) + y = 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 = proto.Field( + proto.FLOAT, + number=1, + ) + y = proto.Field( + proto.FLOAT, + number=2, + ) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[google.cloud.documentai_v1.types.Vertex]): + The bounding polygon vertices. + normalized_vertices (Sequence[google.cloud.documentai_v1.types.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + normalized_vertices = 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..35233364 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/operation_metadata.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + CANCELLING = 2 + SUCCEEDED = 3 + FAILED = 4 + CANCELLED = 5 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + resource = proto.Field( + proto.STRING, + number=5, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = 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..7ebd21e3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor.py @@ -0,0 +1,217 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.documentai_v1.types import document_schema as gcd_document_schema +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. + 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.""" + 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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + replacement_processor_version = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + document_schema = proto.Field( + proto.MESSAGE, + number=12, + message=gcd_document_schema.DocumentSchema, + ) + state = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + kms_key_name = proto.Field( + proto.STRING, + number=9, + ) + kms_key_version_name = proto.Field( + proto.STRING, + number=10, + ) + google_managed = proto.Field( + proto.BOOL, + number=11, + ) + deprecation_info = 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.""" + STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + ENABLING = 3 + DISABLING = 4 + CREATING = 5 + FAILED = 6 + DELETING = 7 + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + default_processor_version = proto.Field( + proto.STRING, + number=9, + ) + process_endpoint = proto.Field( + proto.STRING, + number=6, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + kms_key_name = 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..a4b57cc3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/documentai_v1/types/processor_type.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. +# +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 (Sequence[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 + """ + + 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 = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + category = proto.Field( + proto.STRING, + number=3, + ) + available_locations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=LocationInfo, + ) + allow_creation = proto.Field( + proto.BOOL, + number=6, + ) + launch_stage = proto.Field( + proto.ENUM, + number=8, + enum=launch_stage_pb2.LaunchStage, + ) + + +__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..6f48ca6d --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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", +] + +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.10" + +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-pkg_resources') + 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..ab05d521 --- /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..d5e09e0b --- /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..432fa835 --- /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..d1db083a --- /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..06ee5d32 --- /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..12c59704 --- /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_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_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_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_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..4700daab --- /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..a5169b81 --- /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_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..008f9516 --- /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_documentai_v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_documentai_v1.json new file mode 100644 index 00000000..f534f7d7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_documentai_v1.json @@ -0,0 +1,2735 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.documentai.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-documentai" + }, + "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.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_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_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.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..62a4c9a5 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_documentai_v1_keywords.py @@ -0,0 +1,192 @@ +#! /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', ), + 'fetch_processor_types': ('parent', ), + 'get_processor': ('name', ), + 'get_processor_version': ('name', ), + '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', ), + '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..56c60149 --- /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.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "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, < 2.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"] +if "google.cloud" in packages: + namespaces.append("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", + "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.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt new file mode 100644 index 00000000..2093d40f --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.7.txt @@ -0,0 +1,12 @@ +# 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 +# This file is intentionally left empty to test the +# latest versions of dependencies. +google-api-core==1.33.2 +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..782d686d --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py @@ -0,0 +1,6262 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_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 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"), +]) +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' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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"), +]) +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' + ) + + +def test_document_processor_service_client_get_transport_class(): + transport = DocumentProcessorServiceClient.get_transport_class() + available_transports = [ + transports.DocumentProcessorServiceGrpcTransport, + ] + 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"), +]) +@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"), +]) +@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"), +]) +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), +]) +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.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.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', + ) + + +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, +]) +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 = 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', + 'list_processors', + 'get_processor', + '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', + '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, + ], +) +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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +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' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +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' + ) + +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_human_review_config_path(): + project = "squid" + location = "clam" + processor = "whelk" + 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": "octopus", + "location": "oyster", + "processor": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + processor = "winkle" + 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": "nautilus", + "location": "scallop", + "processor": "abalone", + } + 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 = "squid" + location = "clam" + processor_type = "whelk" + 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": "octopus", + "location": "oyster", + "processor_type": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + processor = "winkle" + processor_version = "nautilus" + 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": "scallop", + "location": "abalone", + "processor": "squid", + "processor_version": "clam", + } + 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 = "whelk" + 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": "octopus", + } + 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 = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentProcessorServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + 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 = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentProcessorServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + 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 = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DocumentProcessorServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + 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 = "scallop" + location = "abalone" + 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": "squid", + "location": "clam", + } + 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_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 = { + "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 = [ + '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..ef619357 --- /dev/null +++ b/owl-bot-staging/v1beta2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/documentai/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound 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..9edede43 --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/documentai_v1beta2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Documentai v1beta2 API +============================================= + +.. automodule:: google.cloud.documentai_v1beta2.types + :members: + :undoc-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..35859c3f --- /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" 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..8c54c884 --- /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 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/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..1749f2f8 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py @@ -0,0 +1,432 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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 variabel 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: ga_credentials.Credentials = None, + transport: Union[str, DocumentUnderstandingServiceTransport] = "grpc_asyncio", + client_options: 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: Union[document_understanding.BatchProcessDocumentsRequest, dict] = None, + *, + requests: Sequence[document_understanding.ProcessDocumentRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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:`Sequence[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: Union[document_understanding.ProcessDocumentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-documentai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..a6f1b4c8 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py @@ -0,0 +1,611 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Optional, Sequence, Tuple, Type, Union, cast +import pkg_resources + +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: 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 variabel 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: Union[str, DocumentUnderstandingServiceTransport, None] = 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: Union[document_understanding.BatchProcessDocumentsRequest, dict] = None, + *, + requests: Sequence[document_understanding.ProcessDocumentRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (Sequence[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: Union[document_understanding.ProcessDocumentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-documentai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..b8d71c60 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import pkg_resources + +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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-documentai', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +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: 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..276d627a --- /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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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: ga_credentials.Credentials = None, + credentials_file: 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..a7dd5f92 --- /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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=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..ad78c55a --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document.py @@ -0,0 +1,1015 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Style]): + Styles for the + [Document.text][google.cloud.documentai.v1beta2.Document.text]. + pages (Sequence[google.cloud.documentai_v1beta2.types.Document.Page]): + Visual page layout for the + [Document][google.cloud.documentai.v1beta2.Document]. + entities (Sequence[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 (Sequence[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 (Sequence[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 = proto.Field( + proto.INT64, + number=1, + ) + shard_count = proto.Field( + proto.INT64, + number=2, + ) + text_offset = 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 = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + name = proto.Field( + proto.STRING, + number=1, + ) + confidence = 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 = proto.Field( + proto.FLOAT, + number=1, + ) + unit = proto.Field( + proto.STRING, + number=2, + ) + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + color = proto.Field( + proto.MESSAGE, + number=2, + message=color_pb2.Color, + ) + background_color = proto.Field( + proto.MESSAGE, + number=3, + message=color_pb2.Color, + ) + font_weight = proto.Field( + proto.STRING, + number=4, + ) + text_style = proto.Field( + proto.STRING, + number=5, + ) + text_decoration = proto.Field( + proto.STRING, + number=6, + ) + font_size = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + blocks (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.Token]): + A list of visually detected tokens on the + page. + visual_elements (Sequence[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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.Table]): + A list of visually detected tables on the + page. + form_fields (Sequence[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 = proto.Field( + proto.FLOAT, + number=1, + ) + height = proto.Field( + proto.FLOAT, + number=2, + ) + unit = 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.""" + ORIENTATION_UNSPECIFIED = 0 + PAGE_UP = 1 + PAGE_RIGHT = 2 + PAGE_DOWN = 3 + PAGE_LEFT = 4 + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + bounding_poly = proto.Field( + proto.MESSAGE, + number=3, + message=geometry.BoundingPoly, + ) + orientation = proto.Field( + proto.ENUM, + number=4, + enum='Document.Page.Layout.Orientation', + ) + id = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = 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 (Sequence[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.""" + TYPE_UNSPECIFIED = 0 + SPACE = 1 + WIDE_SPACE = 2 + HYPHEN = 3 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Document.Page.Token.DetectedBreak.Type', + ) + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_break = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Token.DetectedBreak', + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): + Header rows of the table. + body_rows (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): + Body rows of the table. + detected_languages (Sequence[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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableCell]): + Cells that make up this row. + """ + + cells = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + row_span = proto.Field( + proto.INT32, + number=2, + ) + col_span = proto.Field( + proto.INT32, + number=3, + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + header_rows = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.Table.TableRow', + ) + body_rows = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.Table.TableRow', + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): + A list of detected languages for name + together with confidence. + value_detected_languages (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + field_value = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Layout', + ) + name_detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + value_detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + value_type = proto.Field( + proto.STRING, + number=5, + ) + corrected_key_text = proto.Field( + proto.STRING, + number=6, + ) + corrected_value_text = 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 = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + page_number = proto.Field( + proto.INT32, + number=1, + ) + dimension = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Dimension', + ) + layout = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + blocks = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Document.Page.Block', + ) + paragraphs = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Document.Page.Paragraph', + ) + lines = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Document.Page.Line', + ) + tokens = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Document.Page.Token', + ) + visual_elements = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Document.Page.VisualElement', + ) + tables = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Page.Table', + ) + form_fields = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + mention_text = proto.Field( + proto.STRING, + number=3, + ) + mention_id = proto.Field( + proto.STRING, + number=4, + ) + confidence = proto.Field( + proto.FLOAT, + number=5, + ) + page_anchor = proto.Field( + proto.MESSAGE, + number=6, + message='Document.PageAnchor', + ) + id = 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 = proto.Field( + proto.STRING, + number=1, + ) + object_id = proto.Field( + proto.STRING, + number=2, + ) + relation = 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 (Sequence[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 = proto.Field( + proto.INT64, + number=1, + ) + end_index = proto.Field( + proto.INT64, + number=2, + ) + + text_segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.TextAnchor.TextSegment', + ) + content = 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 (Sequence[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.""" + LAYOUT_TYPE_UNSPECIFIED = 0 + BLOCK = 1 + PARAGRAPH = 2 + LINE = 3 + TOKEN = 4 + VISUAL_ELEMENT = 5 + TABLE = 6 + FORM_FIELD = 7 + + page = proto.Field( + proto.INT64, + number=1, + ) + layout_type = proto.Field( + proto.ENUM, + number=2, + enum='Document.PageAnchor.PageRef.LayoutType', + ) + layout_id = proto.Field( + proto.STRING, + number=3, + ) + + page_refs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.PageAnchor.PageRef', + ) + + uri = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + content = proto.Field( + proto.BYTES, + number=2, + oneof='source', + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + text = proto.Field( + proto.STRING, + number=4, + ) + text_styles = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Style, + ) + pages = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Page, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Entity, + ) + entity_relations = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=EntityRelation, + ) + shard_info = proto.Field( + proto.MESSAGE, + number=9, + message=ShardInfo, + ) + labels = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=Label, + ) + error = 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..c49fd62a --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py @@ -0,0 +1,571 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ProcessDocumentRequest', + ) + parent = 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 = proto.Field( + proto.STRING, + number=9, + ) + input_config = proto.Field( + proto.MESSAGE, + number=1, + message='InputConfig', + ) + output_config = proto.Field( + proto.MESSAGE, + number=2, + message='OutputConfig', + ) + document_type = proto.Field( + proto.STRING, + number=3, + ) + table_extraction_params = proto.Field( + proto.MESSAGE, + number=4, + message='TableExtractionParams', + ) + form_extraction_params = proto.Field( + proto.MESSAGE, + number=5, + message='FormExtractionParams', + ) + entity_extraction_params = proto.Field( + proto.MESSAGE, + number=6, + message='EntityExtractionParams', + ) + ocr_params = proto.Field( + proto.MESSAGE, + number=7, + message='OcrParams', + ) + automl_params = 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 (Sequence[google.cloud.documentai_v1beta2.types.ProcessDocumentResponse]): + Responses for each individual document. + """ + + responses = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='InputConfig', + ) + output_config = proto.Field( + proto.MESSAGE, + number=2, + message='OutputConfig', + ) + + +class OcrParams(proto.Message): + r"""Parameters to control Optical Character Recognition (OCR) + behavior. + + Attributes: + language_hints (Sequence[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 = 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 (Sequence[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 (Sequence[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 = proto.Field( + proto.BOOL, + number=1, + ) + table_bound_hints = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TableBoundHint', + ) + header_hints = proto.RepeatedField( + proto.STRING, + number=3, + ) + model_version = 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 = proto.Field( + proto.INT32, + number=1, + ) + bounding_box = 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 (Sequence[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 = proto.Field( + proto.BOOL, + number=1, + ) + key_value_pair_hints = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='KeyValuePairHint', + ) + model_version = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + value_types = 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 = proto.Field( + proto.BOOL, + number=1, + ) + model_version = 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 = 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 = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsSource', + ) + contents = proto.Field( + proto.BYTES, + number=3, + oneof='source', + ) + mime_type = 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 = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + pages_per_shard = 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 = 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 = 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"""""" + STATE_UNSPECIFIED = 0 + ACCEPTED = 1 + WAITING = 2 + RUNNING = 3 + SUCCEEDED = 4 + CANCELLED = 5 + FAILED = 6 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = 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..54855d7f --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 = proto.Field( + proto.INT32, + number=1, + ) + y = 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 = proto.Field( + proto.FLOAT, + number=1, + ) + y = proto.Field( + proto.FLOAT, + number=2, + ) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[google.cloud.documentai_v1beta2.types.Vertex]): + The bounding polygon vertices. + normalized_vertices (Sequence[google.cloud.documentai_v1beta2.types.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + normalized_vertices = 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..4db89e36 --- /dev/null +++ b/owl-bot-staging/v1beta2/noxfile.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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", +] + +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.10" + +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-pkg_resources') + 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..f7e34352 --- /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_documentai_v1beta2.json b/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_documentai_v1beta2.json new file mode 100644 index 00000000..ba1d80ed --- /dev/null +++ b/owl-bot-staging/v1beta2/samples/generated_samples/snippet_metadata_documentai_v1beta2.json @@ -0,0 +1,328 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.documentai.v1beta2", + "version": "v1beta2" + } + ], + "language": "PYTHON", + "name": "google-cloud-documentai" + }, + "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": "Sequence[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": "Sequence[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..2cd24ecf --- /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.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "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"] +if "google.cloud" in packages: + namespaces.append("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", + "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.7.txt b/owl-bot-staging/v1beta2/testing/constraints-3.7.txt new file mode 100644 index 00000000..aca9f2d3 --- /dev/null +++ b/owl-bot-staging/v1beta2/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# 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 +# This file is intentionally left empty to test the +# latest versions of dependencies. +google-api-core==1.33.2 +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..ef619357 --- /dev/null +++ b/owl-bot-staging/v1beta3/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/documentai/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound 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..7e22aabc --- /dev/null +++ b/owl-bot-staging/v1beta3/docs/documentai_v1beta3/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Documentai v1beta3 API +============================================= + +.. automodule:: google.cloud.documentai_v1beta3.types + :members: + :undoc-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..2f413a68 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai/__init__.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 FetchProcessorTypesRequest +from google.cloud.documentai_v1beta3.types.document_processor_service import FetchProcessorTypesResponse +from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorRequest +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 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 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 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.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', + 'RawDocument', + 'BatchProcessMetadata', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'CreateProcessorRequest', + 'DeleteProcessorMetadata', + 'DeleteProcessorRequest', + 'DeleteProcessorVersionMetadata', + 'DeleteProcessorVersionRequest', + 'DeployProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DisableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'EnableProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + '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..35859c3f --- /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" 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..756936a4 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/__init__.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .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 FetchProcessorTypesRequest +from .types.document_processor_service import FetchProcessorTypesResponse +from .types.document_processor_service import GetProcessorRequest +from .types.document_processor_service import GetProcessorVersionRequest +from .types.document_processor_service import HumanReviewStatus +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 UndeployProcessorVersionMetadata +from .types.document_processor_service import UndeployProcessorVersionRequest +from .types.document_processor_service import UndeployProcessorVersionResponse +from .types.document_schema import DocumentSchema +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', +'FetchProcessorTypesRequest', +'FetchProcessorTypesResponse', +'GcsDocument', +'GcsDocuments', +'GcsPrefix', +'GetProcessorRequest', +'GetProcessorVersionRequest', +'HumanReviewStatus', +'ListProcessorTypesRequest', +'ListProcessorTypesResponse', +'ListProcessorVersionsRequest', +'ListProcessorVersionsResponse', +'ListProcessorsRequest', +'ListProcessorsResponse', +'NormalizedVertex', +'ProcessRequest', +'ProcessResponse', +'Processor', +'ProcessorType', +'ProcessorVersion', +'RawDocument', +'ReviewDocumentOperationMetadata', +'ReviewDocumentRequest', +'ReviewDocumentResponse', +'SetDefaultProcessorVersionMetadata', +'SetDefaultProcessorVersionRequest', +'SetDefaultProcessorVersionResponse', +'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..77ce70c0 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json @@ -0,0 +1,193 @@ + { + "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" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "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" + ] + }, + "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" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "fetch_processor_types" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "GetProcessorVersion": { + "methods": [ + "get_processor_version" + ] + }, + "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" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "undeploy_processor_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..0eb92158 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py @@ -0,0 +1,2415 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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_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 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 + + 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 variabel 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: ga_credentials.Credentials = None, + transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", + client_options: 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: Union[document_processor_service.ProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.BatchProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.FetchProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.ListProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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 list_processors(self, + request: Union[document_processor_service.ListProcessorsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.GetProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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 get_processor_version(self, + request: Union[document_processor_service.GetProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.ListProcessorVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DeleteProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.UndeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.CreateProcessorRequest, dict] = None, + *, + parent: str = None, + processor: gcd_processor.Processor = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DeleteProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.EnableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.DisableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.SetDefaultProcessorVersionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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: Union[document_processor_service.ReviewDocumentRequest, dict] = None, + *, + human_review_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 (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 list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.CancelOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.GetLocationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-documentai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..0598dd30 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py @@ -0,0 +1,2620 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Optional, Sequence, Tuple, Type, Union, cast +import pkg_resources + +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_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 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 + + +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 + + def get_transport_class(cls, + label: 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 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 variabel 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: Union[str, DocumentProcessorServiceTransport, None] = 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: Union[document_processor_service.ProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.BatchProcessRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.FetchProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.ListProcessorTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 list_processors(self, + request: Union[document_processor_service.ListProcessorsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.GetProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 get_processor_version(self, + request: Union[document_processor_service.GetProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.ListProcessorVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DeleteProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.UndeployProcessorVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.CreateProcessorRequest, dict] = None, + *, + parent: str = None, + processor: gcd_processor.Processor = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DeleteProcessorRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.EnableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.DisableProcessorRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.SetDefaultProcessorVersionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: Union[document_processor_service.ReviewDocumentRequest, dict] = None, + *, + human_review_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 __enter__(self): + 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: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: operations_pb2.CancelOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.GetLocationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-documentai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..fe9948c0 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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) 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..d64bf9dd --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_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 DocumentProcessorServiceTransport +from .grpc import DocumentProcessorServiceGrpcTransport +from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] +_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport + +__all__ = ( + 'DocumentProcessorServiceTransport', + 'DocumentProcessorServiceGrpcTransport', + 'DocumentProcessorServiceGrpcAsyncIOTransport', +) 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..7f449b2d --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import pkg_resources + +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 processor +from google.cloud.documentai_v1beta3.types import processor as gcd_processor +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-documentai', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +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: 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.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.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, + ), + } + + 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 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 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 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..2cdc8ed2 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py @@ -0,0 +1,810 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 processor +from google.cloud.documentai_v1beta3.types import processor as gcd_processor +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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: ga_credentials.Credentials = None, + credentials_file: 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 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 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'] + + 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..44cb2f89 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py @@ -0,0 +1,809 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 processor +from google.cloud.documentai_v1beta3.types import processor as gcd_processor +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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=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 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 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'] + + 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/types/__init__.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py new file mode 100644 index 00000000..4eb71575 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + FetchProcessorTypesRequest, + FetchProcessorTypesResponse, + GetProcessorRequest, + GetProcessorVersionRequest, + HumanReviewStatus, + ListProcessorsRequest, + ListProcessorsResponse, + ListProcessorTypesRequest, + ListProcessorTypesResponse, + ListProcessorVersionsRequest, + ListProcessorVersionsResponse, + ProcessRequest, + ProcessResponse, + ReviewDocumentOperationMetadata, + ReviewDocumentRequest, + ReviewDocumentResponse, + SetDefaultProcessorVersionMetadata, + SetDefaultProcessorVersionRequest, + SetDefaultProcessorVersionResponse, + UndeployProcessorVersionMetadata, + UndeployProcessorVersionRequest, + UndeployProcessorVersionResponse, +) +from .document_schema import ( + DocumentSchema, +) +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', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'HumanReviewStatus', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'ProcessRequest', + 'ProcessResponse', + 'ReviewDocumentOperationMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'SetDefaultProcessorVersionMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'DocumentSchema', + '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..855a0ecb --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/barcode.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. +# +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_ = proto.Field( + proto.STRING, + number=1, + ) + value_format = proto.Field( + proto.STRING, + number=2, + ) + raw_value = 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..162f8928 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document.py @@ -0,0 +1,1542 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Style]): + Placeholder. Styles for the + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + pages (Sequence[google.cloud.documentai_v1beta3.types.Document.Page]): + Visual page layout for the + [Document][google.cloud.documentai.v1beta3.Document]. + entities (Sequence[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 (Sequence[google.cloud.documentai_v1beta3.types.Document.EntityRelation]): + Placeholder. Relationship among + [Document.entities][google.cloud.documentai.v1beta3.Document.entities]. + text_changes (Sequence[google.cloud.documentai_v1beta3.types.Document.TextChange]): + Placeholder. A list of text corrections made to + [Document.text]. This is usually used for annotating + corrections to OCR mistakes. Text changes for a given + revision may not overlap with each other. + 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 (Sequence[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 = proto.Field( + proto.INT64, + number=1, + ) + shard_count = proto.Field( + proto.INT64, + number=2, + ) + text_offset = 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. + """ + + 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 = proto.Field( + proto.FLOAT, + number=1, + ) + unit = proto.Field( + proto.STRING, + number=2, + ) + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + color = proto.Field( + proto.MESSAGE, + number=2, + message=color_pb2.Color, + ) + background_color = proto.Field( + proto.MESSAGE, + number=3, + message=color_pb2.Color, + ) + font_weight = proto.Field( + proto.STRING, + number=4, + ) + text_style = proto.Field( + proto.STRING, + number=5, + ) + text_decoration = proto.Field( + proto.STRING, + number=6, + ) + font_size = proto.Field( + proto.MESSAGE, + number=7, + message='Document.Style.FontSize', + ) + + 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 (Sequence[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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + blocks (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.Token]): + A list of visually detected tokens on the + page. + visual_elements (Sequence[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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.Table]): + A list of visually detected tables on the + page. + form_fields (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.FormField]): + A list of visually detected form fields on + the page. + symbols (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.Symbol]): + A list of visually detected symbols on the + page. + detected_barcodes (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedBarcode]): + A list of detected barcodes. + 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 = proto.Field( + proto.FLOAT, + number=1, + ) + height = proto.Field( + proto.FLOAT, + number=2, + ) + unit = 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 = proto.Field( + proto.BYTES, + number=1, + ) + mime_type = proto.Field( + proto.STRING, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + height = 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 = proto.Field( + proto.INT32, + number=1, + ) + cols = proto.Field( + proto.INT32, + number=2, + ) + type_ = proto.Field( + proto.INT32, + number=3, + ) + data = 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.""" + ORIENTATION_UNSPECIFIED = 0 + PAGE_UP = 1 + PAGE_RIGHT = 2 + PAGE_DOWN = 3 + PAGE_LEFT = 4 + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + bounding_poly = proto.Field( + proto.MESSAGE, + number=3, + message=geometry.BoundingPoly, + ) + 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 (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[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.""" + TYPE_UNSPECIFIED = 0 + SPACE = 1 + WIDE_SPACE = 2 + HYPHEN = 3 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Document.Page.Token.DetectedBreak.Type', + ) + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_break = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Token.DetectedBreak', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + 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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + detected_languages = 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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): + Header rows of the table. + body_rows (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): + Body rows of the table. + detected_languages (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + class TableRow(proto.Message): + r"""A row of table cells. + + Attributes: + cells (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableCell]): + Cells that make up this row. + """ + + cells = 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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages together with + confidence. + """ + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + row_span = proto.Field( + proto.INT32, + number=2, + ) + col_span = proto.Field( + proto.INT32, + number=3, + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + + layout = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + header_rows = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Document.Page.Table.TableRow', + ) + body_rows = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.Table.TableRow', + ) + detected_languages = 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_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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): + A list of detected languages for name + together with confidence. + value_detected_languages (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + field_value = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Layout', + ) + name_detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Page.DetectedLanguage', + ) + value_detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + value_type = proto.Field( + proto.STRING, + number=5, + ) + corrected_key_text = proto.Field( + proto.STRING, + number=6, + ) + corrected_value_text = proto.Field( + proto.STRING, + number=7, + ) + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document.Page.Layout', + ) + 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 = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + page_number = proto.Field( + proto.INT32, + number=1, + ) + image = proto.Field( + proto.MESSAGE, + number=13, + message='Document.Page.Image', + ) + transforms = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='Document.Page.Matrix', + ) + dimension = proto.Field( + proto.MESSAGE, + number=2, + message='Document.Page.Dimension', + ) + layout = proto.Field( + proto.MESSAGE, + number=3, + message='Document.Page.Layout', + ) + detected_languages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Document.Page.DetectedLanguage', + ) + blocks = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Document.Page.Block', + ) + paragraphs = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Document.Page.Paragraph', + ) + lines = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Document.Page.Line', + ) + tokens = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Document.Page.Token', + ) + visual_elements = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Document.Page.VisualElement', + ) + tables = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Page.Table', + ) + form_fields = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='Document.Page.FormField', + ) + symbols = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='Document.Page.Symbol', + ) + detected_barcodes = proto.RepeatedField( + proto.MESSAGE, + number=15, + message='Document.Page.DetectedBarcode', + ) + 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 in the document e.g. + ``1600 Amphitheatre Pkwy``. If the entity is not present in + the document, this field will be empty. + 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 (Sequence[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 int + 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 = proto.Field( + proto.MESSAGE, + number=2, + oneof='structured_value', + message=money_pb2.Money, + ) + date_value = proto.Field( + proto.MESSAGE, + number=3, + oneof='structured_value', + message=date_pb2.Date, + ) + datetime_value = proto.Field( + proto.MESSAGE, + number=4, + oneof='structured_value', + message=datetime_pb2.DateTime, + ) + address_value = proto.Field( + proto.MESSAGE, + number=5, + oneof='structured_value', + message=postal_address_pb2.PostalAddress, + ) + boolean_value = proto.Field( + proto.BOOL, + number=6, + oneof='structured_value', + ) + integer_value = proto.Field( + proto.INT32, + number=7, + oneof='structured_value', + ) + float_value = proto.Field( + proto.FLOAT, + number=8, + oneof='structured_value', + ) + text = proto.Field( + proto.STRING, + number=1, + ) + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + mention_text = proto.Field( + proto.STRING, + number=3, + ) + mention_id = proto.Field( + proto.STRING, + number=4, + ) + confidence = proto.Field( + proto.FLOAT, + number=5, + ) + page_anchor = proto.Field( + proto.MESSAGE, + number=6, + message='Document.PageAnchor', + ) + id = proto.Field( + proto.STRING, + number=7, + ) + normalized_value = proto.Field( + proto.MESSAGE, + number=9, + message='Document.Entity.NormalizedValue', + ) + properties = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Document.Entity', + ) + provenance = proto.Field( + proto.MESSAGE, + number=11, + message='Document.Provenance', + ) + redacted = 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 = proto.Field( + proto.STRING, + number=1, + ) + object_id = proto.Field( + proto.STRING, + number=2, + ) + relation = 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 (Sequence[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 = proto.Field( + proto.INT64, + number=1, + ) + end_index = proto.Field( + proto.INT64, + number=2, + ) + + text_segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document.TextAnchor.TextSegment', + ) + content = 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 (Sequence[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.""" + LAYOUT_TYPE_UNSPECIFIED = 0 + BLOCK = 1 + PARAGRAPH = 2 + LINE = 3 + TOKEN = 4 + VISUAL_ELEMENT = 5 + TABLE = 6 + FORM_FIELD = 7 + + page = proto.Field( + proto.INT64, + number=1, + ) + layout_type = proto.Field( + proto.ENUM, + number=2, + enum='Document.PageAnchor.PageRef.LayoutType', + ) + layout_id = proto.Field( + proto.STRING, + number=3, + ) + bounding_poly = proto.Field( + proto.MESSAGE, + number=4, + message=geometry.BoundingPoly, + ) + confidence = proto.Field( + proto.FLOAT, + number=5, + ) + + page_refs = 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 (Sequence[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. + """ + OPERATION_TYPE_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + 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 = proto.Field( + proto.INT32, + number=1, + ) + index = proto.Field( + proto.INT32, + number=3, + ) + id = proto.Field( + proto.INT32, + number=2, + ) + + revision = proto.Field( + proto.INT32, + number=1, + ) + id = proto.Field( + proto.INT32, + number=2, + ) + parents = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance.Parent', + ) + type_ = 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. Unique within the + context of the document. + parent (Sequence[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 (Sequence[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. + 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 = proto.Field( + proto.STRING, + number=1, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + + agent = proto.Field( + proto.STRING, + number=4, + oneof='source', + ) + processor = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + id = proto.Field( + proto.STRING, + number=1, + ) + parent = proto.RepeatedField( + proto.INT32, + number=2, + ) + parent_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + human_review = 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 (Sequence[google.cloud.documentai_v1beta3.types.Document.Provenance]): + The history of this annotation. + """ + + text_anchor = proto.Field( + proto.MESSAGE, + number=1, + message='Document.TextAnchor', + ) + changed_text = proto.Field( + proto.STRING, + number=2, + ) + provenance = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Document.Provenance', + ) + + uri = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + content = proto.Field( + proto.BYTES, + number=2, + oneof='source', + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + text = proto.Field( + proto.STRING, + number=4, + ) + text_styles = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Style, + ) + pages = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Page, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Entity, + ) + entity_relations = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=EntityRelation, + ) + text_changes = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=TextChange, + ) + shard_info = proto.Field( + proto.MESSAGE, + number=9, + message=ShardInfo, + ) + error = proto.Field( + proto.MESSAGE, + number=10, + message=status_pb2.Status, + ) + revisions = 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..1d0574ff --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.documentai.v1beta3', + 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]. + """ + + content = proto.Field( + proto.BYTES, + number=1, + ) + mime_type = 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 = proto.Field( + proto.STRING, + number=1, + ) + mime_type = proto.Field( + proto.STRING, + number=2, + ) + + +class GcsDocuments(proto.Message): + r"""Specifies a set of documents on Cloud Storage. + + Attributes: + documents (Sequence[google.cloud.documentai_v1beta3.types.GcsDocument]): + The list of documents. + """ + + documents = 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 = 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 = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsPrefix', + ) + gcs_documents = 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. + """ + + gcs_uri = proto.Field( + proto.STRING, + number=1, + ) + + gcs_output_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message=GcsOutputConfig, + ) + + +__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..7ca4c45b --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py @@ -0,0 +1,1109 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 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={ + 'ProcessRequest', + 'HumanReviewStatus', + 'ProcessResponse', + 'BatchProcessRequest', + 'BatchProcessResponse', + 'BatchProcessMetadata', + 'FetchProcessorTypesRequest', + 'FetchProcessorTypesResponse', + 'ListProcessorTypesRequest', + 'ListProcessorTypesResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'GetProcessorRequest', + 'GetProcessorVersionRequest', + 'ListProcessorVersionsRequest', + 'ListProcessorVersionsResponse', + 'DeleteProcessorVersionRequest', + 'DeleteProcessorVersionMetadata', + 'DeployProcessorVersionRequest', + 'DeployProcessorVersionResponse', + 'DeployProcessorVersionMetadata', + 'UndeployProcessorVersionRequest', + 'UndeployProcessorVersionResponse', + 'UndeployProcessorVersionMetadata', + 'CreateProcessorRequest', + 'DeleteProcessorRequest', + 'DeleteProcessorMetadata', + 'EnableProcessorRequest', + 'EnableProcessorResponse', + 'EnableProcessorMetadata', + 'DisableProcessorRequest', + 'DisableProcessorResponse', + 'DisableProcessorMetadata', + 'SetDefaultProcessorVersionRequest', + 'SetDefaultProcessorVersionResponse', + 'SetDefaultProcessorVersionMetadata', + 'ReviewDocumentRequest', + 'ReviewDocumentResponse', + 'ReviewDocumentOperationMetadata', + }, +) + + +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. + """ + + inline_document = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + raw_document = proto.Field( + proto.MESSAGE, + number=5, + oneof='source', + message=document_io.RawDocument, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + skip_human_review = proto.Field( + proto.BOOL, + number=3, + ) + field_mask = 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_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.""" + STATE_UNSPECIFIED = 0 + SKIPPED = 1 + VALIDATION_PASSED = 2 + IN_PROGRESS = 3 + ERROR = 4 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + human_review_operation = 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 = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + human_review_operation = proto.Field( + proto.STRING, + number=2, + ) + human_review_status = 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 (Sequence[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. + """ + + 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 = proto.Field( + proto.STRING, + number=1, + ) + mime_type = 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 = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + input_configs = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=BatchInputConfig, + ) + output_config = proto.Field( + proto.MESSAGE, + number=3, + message=BatchOutputConfig, + ) + input_documents = proto.Field( + proto.MESSAGE, + number=5, + message=document_io.BatchDocumentsInputConfig, + ) + document_output_config = proto.Field( + proto.MESSAGE, + number=6, + message=document_io.DocumentOutputConfig, + ) + skip_human_review = 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_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 (Sequence[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.""" + 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 = proto.Field( + proto.STRING, + number=1, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + output_gcs_destination = proto.Field( + proto.STRING, + number=3, + ) + human_review_operation = proto.Field( + proto.STRING, + number=4, + ) + human_review_status = proto.Field( + proto.MESSAGE, + number=5, + message='HumanReviewStatus', + ) + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + individual_process_statuses = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchProcessorTypesResponse(proto.Message): + r"""Response message for fetch processor types. + + Attributes: + processor_types (Sequence[google.cloud.documentai_v1beta3.types.ProcessorType]): + The list of processor types. + """ + + processor_types = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListProcessorTypesResponse(proto.Message): + r"""Response message for list processor types. + + Attributes: + processor_types (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=processor_type.ProcessorType, + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListProcessorsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processors (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.Processor, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetProcessorRequest(proto.Message): + r"""Request message for get processor. + + Attributes: + name (str): + Required. The processor resource name. + """ + + name = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListProcessorVersionsResponse(proto.Message): + r"""Response message for list processors. + + Attributes: + processor_versions (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_processor.ProcessorVersion, + ) + next_page_token = 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 = 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 = 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 = 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 = 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 = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + 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 = 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 = 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 = 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 = 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 = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + default_processor_version = 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 = proto.Field( + proto.MESSAGE, + number=1, + message=operation_metadata.CommonOperationMetadata, + ) + + +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.""" + DEFAULT = 0 + URGENT = 1 + + inline_document = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=gcd_document.Document, + ) + human_review_config = proto.Field( + proto.STRING, + number=1, + ) + document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + enable_schema_validation = proto.Field( + proto.BOOL, + number=3, + ) + priority = proto.Field( + proto.ENUM, + number=5, + enum=Priority, + ) + document_schema = 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.""" + STATE_UNSPECIFIED = 0 + REJECTED = 1 + SUCCEEDED = 2 + + gcs_destination = proto.Field( + proto.STRING, + number=1, + ) + state = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + rejection_reason = 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.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + CANCELLING = 2 + SUCCEEDED = 3 + FAILED = 4 + CANCELLED = 5 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + common_metadata = proto.Field( + proto.MESSAGE, + number=5, + message=operation_metadata.CommonOperationMetadata, + ) + question_id = proto.Field( + proto.STRING, + number=6, + ) + + +__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..deb3a0da --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py @@ -0,0 +1,224 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[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-insensitive + - Maximum 64 characters. + - Must start with a letter. + - Allowed characters: ASCII letters ``[a-z0-9_-]``. (For + backward compatibility internal infrastructure and + tooling can handle any ascii character) + - The '/' is sometimes used to denote a property of a type. + For example line_item/amount. This convention is + deprecated, but will still be honored for backward + compatibility. + base_types (Sequence[str]): + The entity type that this type is derived + from. For now, one and only one should be set. + properties (Sequence[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 (Sequence[str]): + The individual values that this enum values + type can include. + """ + + values = 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. + """ + OCCURRENCE_TYPE_UNSPECIFIED = 0 + OPTIONAL_ONCE = 1 + OPTIONAL_MULTIPLE = 2 + REQUIRED_ONCE = 3 + REQUIRED_MULTIPLE = 4 + + name = proto.Field( + proto.STRING, + number=1, + ) + value_type = proto.Field( + proto.STRING, + number=2, + ) + occurrence_type = proto.Field( + proto.ENUM, + number=3, + enum='DocumentSchema.EntityType.Property.OccurrenceType', + ) + + enum_values = proto.Field( + proto.MESSAGE, + number=14, + oneof='value_source', + message='DocumentSchema.EntityType.EnumValues', + ) + display_name = proto.Field( + proto.STRING, + number=13, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + base_types = proto.RepeatedField( + proto.STRING, + number=2, + ) + properties = 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 = proto.Field( + proto.BOOL, + number=1, + ) + document_allow_multiple_labels = proto.Field( + proto.BOOL, + number=2, + ) + prefixed_naming_on_properties = proto.Field( + proto.BOOL, + number=6, + ) + skip_naming_validation = proto.Field( + proto.BOOL, + number=7, + ) + + display_name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=EntityType, + ) + 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/geometry.py b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py new file mode 100644 index 00000000..b81181e8 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/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. +# +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 = proto.Field( + proto.INT32, + number=1, + ) + y = 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 = proto.Field( + proto.FLOAT, + number=1, + ) + y = proto.Field( + proto.FLOAT, + number=2, + ) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[google.cloud.documentai_v1beta3.types.Vertex]): + The bounding polygon vertices. + normalized_vertices (Sequence[google.cloud.documentai_v1beta3.types.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + normalized_vertices = 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..0c7780a3 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + CANCELLING = 2 + SUCCEEDED = 3 + FAILED = 4 + CANCELLED = 5 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message = proto.Field( + proto.STRING, + number=2, + ) + resource = proto.Field( + proto.STRING, + number=5, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = 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..53e4d171 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +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. + 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. + 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.""" + 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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + replacement_processor_version = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + kms_key_name = proto.Field( + proto.STRING, + number=9, + ) + kms_key_version_name = proto.Field( + proto.STRING, + number=10, + ) + google_managed = proto.Field( + proto.BOOL, + number=11, + ) + deprecation_info = 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.""" + STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + ENABLING = 3 + DISABLING = 4 + CREATING = 5 + FAILED = 6 + DELETING = 7 + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + default_processor_version = proto.Field( + proto.STRING, + number=9, + ) + process_endpoint = proto.Field( + proto.STRING, + number=6, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + kms_key_name = 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..b7972355 --- /dev/null +++ b/owl-bot-staging/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.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. +# +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 type of the processor, e.g., "invoice_parsing". + category (str): + The processor category, used by UI to group + processor types. + available_locations (Sequence[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 + """ + + 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 = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + category = proto.Field( + proto.STRING, + number=3, + ) + available_locations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=LocationInfo, + ) + allow_creation = proto.Field( + proto.BOOL, + number=6, + ) + launch_stage = proto.Field( + proto.ENUM, + number=8, + enum=launch_stage_pb2.LaunchStage, + ) + + +__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..1d65f1ad --- /dev/null +++ b/owl-bot-staging/v1beta3/noxfile.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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", +] + +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.10" + +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-pkg_resources') + 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..dd97b90e --- /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..b8397493 --- /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..229084ec --- /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..9f279130 --- /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..2038e476 --- /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..2ad6428a --- /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_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_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_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_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..719b19ae --- /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..b1b1fa67 --- /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_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..0aa0e74f --- /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_documentai_v1beta3.json b/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_documentai_v1beta3.json new file mode 100644 index 00000000..860bdc9f --- /dev/null +++ b/owl-bot-staging/v1beta3/samples/generated_samples/snippet_metadata_documentai_v1beta3.json @@ -0,0 +1,2735 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.documentai.v1beta3", + "version": "v1beta3" + } + ], + "language": "PYTHON", + "name": "google-cloud-documentai" + }, + "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.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_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_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.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..494d0855 --- /dev/null +++ b/owl-bot-staging/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py @@ -0,0 +1,192 @@ +#! /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', ), + 'create_processor': ('parent', 'processor', ), + 'delete_processor': ('name', ), + 'delete_processor_version': ('name', ), + 'deploy_processor_version': ('name', ), + 'disable_processor': ('name', ), + 'enable_processor': ('name', ), + 'fetch_processor_types': ('parent', ), + 'get_processor': ('name', ), + 'get_processor_version': ('name', ), + 'list_processors': ('parent', 'page_size', 'page_token', ), + 'list_processor_types': ('parent', 'page_size', 'page_token', ), + 'list_processor_versions': ('parent', 'page_size', 'page_token', ), + 'process_document': ('name', 'inline_document', 'raw_document', 'document', 'skip_human_review', 'field_mask', ), + 'review_document': ('human_review_config', 'inline_document', 'document', 'enable_schema_validation', 'priority', 'document_schema', ), + 'set_default_processor_version': ('processor', 'default_processor_version', ), + '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..2cd24ecf --- /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.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "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"] +if "google.cloud" in packages: + namespaces.append("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", + "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.7.txt b/owl-bot-staging/v1beta3/testing/constraints-3.7.txt new file mode 100644 index 00000000..aca9f2d3 --- /dev/null +++ b/owl-bot-staging/v1beta3/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# 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 +# This file is intentionally left empty to test the +# latest versions of dependencies. +google-api-core==1.33.2 +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..75139cd4 --- /dev/null +++ b/owl-bot-staging/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py @@ -0,0 +1,6266 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_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 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"), +]) +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' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentProcessorServiceGrpcTransport, "grpc"), + (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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"), +]) +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' + ) + + +def test_document_processor_service_client_get_transport_class(): + transport = DocumentProcessorServiceClient.get_transport_class() + available_transports = [ + transports.DocumentProcessorServiceGrpcTransport, + ] + 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"), +]) +@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"), +]) +@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"), +]) +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), +]) +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.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.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', + ) + + +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, +]) +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 = 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', + 'list_processors', + 'get_processor', + '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', + '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, + ], +) +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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +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' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +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' + ) + +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_human_review_config_path(): + project = "squid" + location = "clam" + processor = "whelk" + 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": "octopus", + "location": "oyster", + "processor": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + processor = "winkle" + 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": "nautilus", + "location": "scallop", + "processor": "abalone", + } + 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 = "squid" + location = "clam" + processor_type = "whelk" + 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": "octopus", + "location": "oyster", + "processor_type": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + processor = "winkle" + processor_version = "nautilus" + 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": "scallop", + "location": "abalone", + "processor": "squid", + "processor_version": "clam", + } + 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 = "whelk" + 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": "octopus", + } + 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 = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentProcessorServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + 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 = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentProcessorServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + 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 = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DocumentProcessorServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + 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 = "scallop" + location = "abalone" + 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": "squid", + "location": "clam", + } + 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_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 = { + "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 = [ + '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, + )