diff --git a/owl-bot-staging/google-cloud-documentai/v1/.coveragerc b/owl-bot-staging/google-cloud-documentai/v1/.coveragerc deleted file mode 100644 index 46ab6093e34b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/documentai/__init__.py - google/cloud/documentai/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-documentai/v1/.flake8 b/owl-bot-staging/google-cloud-documentai/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-documentai/v1/MANIFEST.in b/owl-bot-staging/google-cloud-documentai/v1/MANIFEST.in deleted file mode 100644 index b804f1572981..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/documentai *.py -recursive-include google/cloud/documentai_v1 *.py diff --git a/owl-bot-staging/google-cloud-documentai/v1/README.rst b/owl-bot-staging/google-cloud-documentai/v1/README.rst deleted file mode 100644 index 484a3c1c8fa7..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Documentai API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Documentai API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-documentai/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-documentai/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-documentai/v1/docs/conf.py b/owl-bot-staging/google-cloud-documentai/v1/docs/conf.py deleted file mode 100644 index 8d93c59cdbb8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2023, 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 = 'en' - -# 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/google-cloud-documentai/v1/docs/documentai_v1/document_processor_service.rst b/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/document_processor_service.rst deleted file mode 100644 index 5288f946dad1..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/document_processor_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentProcessorService ------------------------------------------- - -.. automodule:: google.cloud.documentai_v1.services.document_processor_service - :members: - :inherited-members: - -.. automodule:: google.cloud.documentai_v1.services.document_processor_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/services_.rst b/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/services_.rst deleted file mode 100644 index 551bb666953f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Documentai v1 API -=========================================== -.. toctree:: - :maxdepth: 2 - - document_processor_service diff --git a/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/types_.rst b/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/types_.rst deleted file mode 100644 index ddfb0aac910f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/docs/documentai_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Documentai v1 API -======================================== - -.. automodule:: google.cloud.documentai_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-documentai/v1/docs/index.rst b/owl-bot-staging/google-cloud-documentai/v1/docs/index.rst deleted file mode 100644 index c907db5bf4d2..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - documentai_v1/services - documentai_v1/types diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/__init__.py deleted file mode 100644 index 30e09b4d0d1b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/__init__.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 OcrConfig -from google.cloud.documentai_v1.types.document_io import RawDocument -from google.cloud.documentai_v1.types.document_processor_service import BatchProcessMetadata -from google.cloud.documentai_v1.types.document_processor_service import BatchProcessRequest -from google.cloud.documentai_v1.types.document_processor_service import BatchProcessResponse -from google.cloud.documentai_v1.types.document_processor_service import CreateProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorMetadata -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import DeleteProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import DeployProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorMetadata -from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import DisableProcessorResponse -from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorMetadata -from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import EnableProcessorResponse -from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import EvaluateProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import FetchProcessorTypesRequest -from google.cloud.documentai_v1.types.document_processor_service import FetchProcessorTypesResponse -from google.cloud.documentai_v1.types.document_processor_service import GetEvaluationRequest -from google.cloud.documentai_v1.types.document_processor_service import GetProcessorRequest -from google.cloud.documentai_v1.types.document_processor_service import GetProcessorTypeRequest -from google.cloud.documentai_v1.types.document_processor_service import GetProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import HumanReviewStatus -from google.cloud.documentai_v1.types.document_processor_service import ListEvaluationsRequest -from google.cloud.documentai_v1.types.document_processor_service import ListEvaluationsResponse -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorsRequest -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorsResponse -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorTypesRequest -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorTypesResponse -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorVersionsRequest -from google.cloud.documentai_v1.types.document_processor_service import ListProcessorVersionsResponse -from google.cloud.documentai_v1.types.document_processor_service import ProcessOptions -from google.cloud.documentai_v1.types.document_processor_service import ProcessRequest -from google.cloud.documentai_v1.types.document_processor_service import ProcessResponse -from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentOperationMetadata -from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentRequest -from google.cloud.documentai_v1.types.document_processor_service import ReviewDocumentResponse -from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import SetDefaultProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import TrainProcessorVersionResponse -from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionMetadata -from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionRequest -from google.cloud.documentai_v1.types.document_processor_service import UndeployProcessorVersionResponse -from google.cloud.documentai_v1.types.document_schema import DocumentSchema -from google.cloud.documentai_v1.types.evaluation import Evaluation -from google.cloud.documentai_v1.types.evaluation import EvaluationReference -from google.cloud.documentai_v1.types.geometry import BoundingPoly -from google.cloud.documentai_v1.types.geometry import NormalizedVertex -from google.cloud.documentai_v1.types.geometry import Vertex -from google.cloud.documentai_v1.types.operation_metadata import CommonOperationMetadata -from google.cloud.documentai_v1.types.processor import Processor -from google.cloud.documentai_v1.types.processor import ProcessorVersion -from google.cloud.documentai_v1.types.processor import ProcessorVersionAlias -from google.cloud.documentai_v1.types.processor_type import ProcessorType - -__all__ = ('DocumentProcessorServiceClient', - 'DocumentProcessorServiceAsyncClient', - 'Barcode', - 'Document', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'OcrConfig', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessOptions', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorVersionAlias', - 'ProcessorType', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/gapic_version.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/py.typed b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/py.typed deleted file mode 100644 index 81b450017987..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/__init__.py deleted file mode 100644 index 1128fbeede87..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/__init__.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.documentai_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.document_processor_service import DocumentProcessorServiceClient -from .services.document_processor_service import DocumentProcessorServiceAsyncClient - -from .types.barcode import Barcode -from .types.document import Document -from .types.document_io import BatchDocumentsInputConfig -from .types.document_io import DocumentOutputConfig -from .types.document_io import GcsDocument -from .types.document_io import GcsDocuments -from .types.document_io import GcsPrefix -from .types.document_io import OcrConfig -from .types.document_io import RawDocument -from .types.document_processor_service import BatchProcessMetadata -from .types.document_processor_service import BatchProcessRequest -from .types.document_processor_service import BatchProcessResponse -from .types.document_processor_service import CreateProcessorRequest -from .types.document_processor_service import DeleteProcessorMetadata -from .types.document_processor_service import DeleteProcessorRequest -from .types.document_processor_service import DeleteProcessorVersionMetadata -from .types.document_processor_service import DeleteProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionMetadata -from .types.document_processor_service import DeployProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionResponse -from .types.document_processor_service import DisableProcessorMetadata -from .types.document_processor_service import DisableProcessorRequest -from .types.document_processor_service import DisableProcessorResponse -from .types.document_processor_service import EnableProcessorMetadata -from .types.document_processor_service import EnableProcessorRequest -from .types.document_processor_service import EnableProcessorResponse -from .types.document_processor_service import EvaluateProcessorVersionMetadata -from .types.document_processor_service import EvaluateProcessorVersionRequest -from .types.document_processor_service import EvaluateProcessorVersionResponse -from .types.document_processor_service import FetchProcessorTypesRequest -from .types.document_processor_service import FetchProcessorTypesResponse -from .types.document_processor_service import GetEvaluationRequest -from .types.document_processor_service import GetProcessorRequest -from .types.document_processor_service import GetProcessorTypeRequest -from .types.document_processor_service import GetProcessorVersionRequest -from .types.document_processor_service import HumanReviewStatus -from .types.document_processor_service import ListEvaluationsRequest -from .types.document_processor_service import ListEvaluationsResponse -from .types.document_processor_service import ListProcessorsRequest -from .types.document_processor_service import ListProcessorsResponse -from .types.document_processor_service import ListProcessorTypesRequest -from .types.document_processor_service import ListProcessorTypesResponse -from .types.document_processor_service import ListProcessorVersionsRequest -from .types.document_processor_service import ListProcessorVersionsResponse -from .types.document_processor_service import ProcessOptions -from .types.document_processor_service import ProcessRequest -from .types.document_processor_service import ProcessResponse -from .types.document_processor_service import ReviewDocumentOperationMetadata -from .types.document_processor_service import ReviewDocumentRequest -from .types.document_processor_service import ReviewDocumentResponse -from .types.document_processor_service import SetDefaultProcessorVersionMetadata -from .types.document_processor_service import SetDefaultProcessorVersionRequest -from .types.document_processor_service import SetDefaultProcessorVersionResponse -from .types.document_processor_service import TrainProcessorVersionMetadata -from .types.document_processor_service import TrainProcessorVersionRequest -from .types.document_processor_service import TrainProcessorVersionResponse -from .types.document_processor_service import UndeployProcessorVersionMetadata -from .types.document_processor_service import UndeployProcessorVersionRequest -from .types.document_processor_service import UndeployProcessorVersionResponse -from .types.document_schema import DocumentSchema -from .types.evaluation import Evaluation -from .types.evaluation import EvaluationReference -from .types.geometry import BoundingPoly -from .types.geometry import NormalizedVertex -from .types.geometry import Vertex -from .types.operation_metadata import CommonOperationMetadata -from .types.processor import Processor -from .types.processor import ProcessorVersion -from .types.processor import ProcessorVersionAlias -from .types.processor_type import ProcessorType - -__all__ = ( - 'DocumentProcessorServiceAsyncClient', -'Barcode', -'BatchDocumentsInputConfig', -'BatchProcessMetadata', -'BatchProcessRequest', -'BatchProcessResponse', -'BoundingPoly', -'CommonOperationMetadata', -'CreateProcessorRequest', -'DeleteProcessorMetadata', -'DeleteProcessorRequest', -'DeleteProcessorVersionMetadata', -'DeleteProcessorVersionRequest', -'DeployProcessorVersionMetadata', -'DeployProcessorVersionRequest', -'DeployProcessorVersionResponse', -'DisableProcessorMetadata', -'DisableProcessorRequest', -'DisableProcessorResponse', -'Document', -'DocumentOutputConfig', -'DocumentProcessorServiceClient', -'DocumentSchema', -'EnableProcessorMetadata', -'EnableProcessorRequest', -'EnableProcessorResponse', -'EvaluateProcessorVersionMetadata', -'EvaluateProcessorVersionRequest', -'EvaluateProcessorVersionResponse', -'Evaluation', -'EvaluationReference', -'FetchProcessorTypesRequest', -'FetchProcessorTypesResponse', -'GcsDocument', -'GcsDocuments', -'GcsPrefix', -'GetEvaluationRequest', -'GetProcessorRequest', -'GetProcessorTypeRequest', -'GetProcessorVersionRequest', -'HumanReviewStatus', -'ListEvaluationsRequest', -'ListEvaluationsResponse', -'ListProcessorTypesRequest', -'ListProcessorTypesResponse', -'ListProcessorVersionsRequest', -'ListProcessorVersionsResponse', -'ListProcessorsRequest', -'ListProcessorsResponse', -'NormalizedVertex', -'OcrConfig', -'ProcessOptions', -'ProcessRequest', -'ProcessResponse', -'Processor', -'ProcessorType', -'ProcessorVersion', -'ProcessorVersionAlias', -'RawDocument', -'ReviewDocumentOperationMetadata', -'ReviewDocumentRequest', -'ReviewDocumentResponse', -'SetDefaultProcessorVersionMetadata', -'SetDefaultProcessorVersionRequest', -'SetDefaultProcessorVersionResponse', -'TrainProcessorVersionMetadata', -'TrainProcessorVersionRequest', -'TrainProcessorVersionResponse', -'UndeployProcessorVersionMetadata', -'UndeployProcessorVersionRequest', -'UndeployProcessorVersionResponse', -'Vertex', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/gapic_metadata.json deleted file mode 100644 index 863c39a36917..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/gapic_metadata.json +++ /dev/null @@ -1,358 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.documentai_v1", - "protoPackage": "google.cloud.documentai.v1", - "schema": "1.0", - "services": { - "DocumentProcessorService": { - "clients": { - "grpc": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentProcessorServiceAsyncClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/gapic_version.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/py.typed b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/py.typed deleted file mode 100644 index 81b450017987..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py deleted file mode 100644 index 326eb2c14112..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py deleted file mode 100644 index 1bec884a525a..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/async_client.py +++ /dev/null @@ -1,3127 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.documentai_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1.services.document_processor_service import pagers -from google.cloud.documentai_v1.types import document -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import document_schema -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -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 Document AI 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 - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DocumentProcessorServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - - evaluation_path = staticmethod(DocumentProcessorServiceClient.evaluation_path) - parse_evaluation_path = staticmethod(DocumentProcessorServiceClient.parse_evaluation_path) - human_review_config_path = staticmethod(DocumentProcessorServiceClient.human_review_config_path) - parse_human_review_config_path = staticmethod(DocumentProcessorServiceClient.parse_human_review_config_path) - processor_path = staticmethod(DocumentProcessorServiceClient.processor_path) - parse_processor_path = staticmethod(DocumentProcessorServiceClient.parse_processor_path) - processor_type_path = staticmethod(DocumentProcessorServiceClient.processor_type_path) - parse_processor_type_path = staticmethod(DocumentProcessorServiceClient.parse_processor_type_path) - processor_version_path = staticmethod(DocumentProcessorServiceClient.processor_version_path) - parse_processor_version_path = staticmethod(DocumentProcessorServiceClient.parse_processor_version_path) - common_billing_account_path = staticmethod(DocumentProcessorServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentProcessorServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentProcessorServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentProcessorServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentProcessorServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentProcessorServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentProcessorServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentProcessorServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentProcessorServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentProcessorServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_info.__func__(DocumentProcessorServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_file.__func__(DocumentProcessorServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentProcessorServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = functools.partial(type(DocumentProcessorServiceClient).get_transport_class, type(DocumentProcessorServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service async 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. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = DocumentProcessorServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_process_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ProcessRequest, dict]]): - The request object. Request message for the - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - 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.AsyncRetry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_batch_process_documents(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.BatchProcessRequest, dict]]): - The request object. Request message for - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - """ - # 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.AsyncRetry( -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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - async def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we don't use - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - here, because it isn't paginated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_fetch_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.fetch_processor_types(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.FetchProcessorTypesRequest, dict]]): - The request object. Request message for the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (:class:`str`): - Required. The location of processor types to list. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesAsyncPager: - r"""Lists the processor types that exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_list_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorTypesRequest, dict]]): - The request object. Request message for the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (:class:`str`): - Required. The location of processor types to list. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProcessorTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorTypeRequest, dict]]): - The request object. Request message for the - [GetProcessorType][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType] - method. - name (:class:`str`): - Required. The processor type resource - name. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.types.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.GetProcessorTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_processor_type, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsAsyncPager: - r"""Lists all processors which belong to this project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_list_processors(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorsRequest, dict]]): - The request object. Request message for list all - processors belongs to a project. - parent (:class:`str`): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ListProcessors][google.cloud.documentai.v1.DocumentProcessorService.ListProcessors] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProcessorsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_get_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorRequest, dict]]): - The request object. Request message for the - [GetProcessor][google.cloud.documentai.v1.DocumentProcessorService.GetProcessor] - method. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def train_processor_version(self, - request: Optional[Union[document_processor_service.TrainProcessorVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor_version: Optional[processor.ProcessorVersion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1.TrainProcessorVersionMetadata]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_train_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.TrainProcessorVersionRequest, dict]]): - The request object. Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion] - method. - parent (:class:`str`): - Required. The parent (project, location and processor) - to create the new version for. Format: - ``projects/{project}/locations/{location}/processors/{processor}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor_version (:class:`google.cloud.documentai_v1.types.ProcessorVersion`): - Required. The processor version to be - created. - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1.types.TrainProcessorVersionResponse` The response for - [TrainProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, processor_version]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.TrainProcessorVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.train_processor_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.TrainProcessorVersionResponse, - metadata_type=document_processor_service.TrainProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def get_processor_version(self, - request: Optional[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_get_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.GetProcessorVersionRequest, dict]]): - The request object. Request message for the - [GetProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion] - method. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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, - pretrained by Google internally or - uptrained by the customer. A processor - can only have one default version at a - time. Its document-processing behavior - is defined by that 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsAsyncPager: - r"""Lists all versions of a processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_list_processor_versions(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ListProcessorVersionsRequest, dict]]): - The request object. Request message for list all - processor versions belongs to a - processor. - parent (:class:`str`): - Required. The parent (project, location and processor) - to list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ListProcessorVersions][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProcessorVersionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_delete_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.DeleteProcessorVersionRequest, dict]]): - The request object. Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_deploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.DeployProcessorVersionRequest, dict]]): - The request object. Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Undeploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.UndeployProcessorVersionRequest, dict]]): - The request object. Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] - provided. The processor will be at ``ENABLED`` state by default - after its creation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_create_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.CreateProcessorRequest, dict]]): - The request object. Request message for the - [CreateProcessor][google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized - backend service. If the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] - isn't available in that region, the creation fails. - 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][google.cloud.documentai.v1.Processor.type] - and - [Processor.display_name][google.cloud.documentai.v1.Processor.display_name] - to be set. Also, the - [Processor.kms_key_name][google.cloud.documentai.v1.Processor.kms_key_name] - field must be set if the processor is under CMEK. - - This corresponds to the ``processor`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_delete_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.DeleteProcessorRequest, dict]]): - The request object. Request message for the - [DeleteProcessor][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - async def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Enables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_enable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.EnableProcessorRequest, dict]]): - The request object. Request message for the - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Disables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_disable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.DisableProcessorRequest, dict]]): - The request object. Request message for the - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_set_default_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest, dict]]): - The request object. Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_review_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ReviewDocumentRequest, dict]]): - The request object. Request message for the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - method. - human_review_config (:class:`str`): - Required. The resource name of the - [HumanReviewConfig][google.cloud.documentai.v1.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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - 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.AsyncRetry( -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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # Done; return the response. - return response - - async def evaluate_processor_version(self, - request: Optional[Union[document_processor_service.EvaluateProcessorVersionRequest, dict]] = None, - *, - processor_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.EvaluateProcessorVersionRequest, dict]]): - The request object. Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - against the supplied documents. - processor_version (:class:`str`): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to evaluate. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1.types.EvaluateProcessorVersionResponse` Response of the - [EvaluateProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([processor_version]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.EvaluateProcessorVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.evaluate_processor_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("processor_version", request.processor_version), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.EvaluateProcessorVersionResponse, - metadata_type=document_processor_service.EvaluateProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def get_evaluation(self, - request: Optional[Union[document_processor_service.GetEvaluationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation.Evaluation: - r"""Retrieves a specific evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_get_evaluation(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_evaluation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.GetEvaluationRequest, dict]]): - The request object. Retrieves a specific Evaluation. - name (:class:`str`): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1.Evaluation] to - get. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.types.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.GetEvaluationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_evaluation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_evaluations(self, - request: Optional[Union[document_processor_service.ListEvaluationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEvaluationsAsyncPager: - r"""Retrieves a set of evaluations for a given processor - version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - async def sample_list_evaluations(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1.types.ListEvaluationsRequest, dict]]): - The request object. Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - parent (:class:`str`): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to list evaluations for. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.services.document_processor_service.pagers.ListEvaluationsAsyncPager: - The response from ListEvaluations. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.ListEvaluationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_evaluations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEvaluationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DocumentProcessorServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/client.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/client.py deleted file mode 100644 index 3fb58ea490eb..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/client.py +++ /dev/null @@ -1,3492 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.documentai_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1.services.document_processor_service import pagers -from google.cloud.documentai_v1.types import document -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import document_schema -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentProcessorServiceGrpcTransport -from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .transports.rest import DocumentProcessorServiceRestTransport - - -class DocumentProcessorServiceClientMeta(type): - """Metaclass for the DocumentProcessorService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] - _transport_registry["grpc"] = DocumentProcessorServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentProcessorServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentProcessorServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentProcessorServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentProcessorServiceClient(metaclass=DocumentProcessorServiceClientMeta): - """Service to call Document AI 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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "documentai.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "documentai.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def evaluation_path(project: str,location: str,processor: str,processor_version: str,evaluation: str,) -> str: - """Returns a fully-qualified evaluation string.""" - return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}".format(project=project, location=location, processor=processor, processor_version=processor_version, evaluation=evaluation, ) - - @staticmethod - def parse_evaluation_path(path: str) -> Dict[str,str]: - """Parses a evaluation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)/evaluations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def human_review_config_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified human_review_config string.""" - return "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_human_review_config_path(path: str) -> Dict[str,str]: - """Parses a human_review_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/humanReviewConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified processor string.""" - return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_processor_path(path: str) -> Dict[str,str]: - """Parses a processor path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_type_path(project: str,location: str,processor_type: str,) -> str: - """Returns a fully-qualified processor_type string.""" - return "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - - @staticmethod - def parse_processor_type_path(path: str) -> Dict[str,str]: - """Parses a processor_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processorTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_version_path(project: str,location: str,processor: str,processor_version: str,) -> str: - """Returns a fully-qualified processor_version string.""" - return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - - @staticmethod - def parse_processor_version_path(path: str) -> Dict[str,str]: - """Parses a processor_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - 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 - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - 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`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DocumentProcessorServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentProcessorServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DocumentProcessorServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = DocumentProcessorServiceClient._read_environment_variables() - self._client_cert_source = DocumentProcessorServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DocumentProcessorServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._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. - transport_provided = isinstance(transport, DocumentProcessorServiceTransport) - if transport_provided: - # transport is a DocumentProcessorServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(DocumentProcessorServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DocumentProcessorServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - 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(cast(str, transport)) - self._transport = Transport( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_process_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ProcessRequest, dict]): - The request object. Request message for the - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - 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 - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_batch_process_documents(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.BatchProcessRequest, dict]): - The request object. Request message for - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - 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 - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - """ - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we don't use - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - here, because it isn't 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 the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (str): - Required. The location of processor types to list. - 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 the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesPager: - r"""Lists the processor types that exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_list_processor_types(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ListProcessorTypesRequest, dict]): - The request object. Request message for the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (str): - Required. The location of processor types to list. - 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 the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProcessorTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetProcessorTypeRequest, dict]): - The request object. Request message for the - [GetProcessorType][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType] - method. - name (str): - Required. The processor type resource - name. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.types.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.GetProcessorTypeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.GetProcessorTypeRequest): - request = document_processor_service.GetProcessorTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_processor_type] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsPager: - r"""Lists all processors which belong to this project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_list_processors(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ListProcessorsRequest, dict]): - The request object. Request message for list all - processors belongs to a project. - parent (str): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorsPager: - Response message for the - [ListProcessors][google.cloud.documentai.v1.DocumentProcessorService.ListProcessors] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProcessorsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_get_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetProcessorRequest, dict]): - The request object. Request message for the - [GetProcessor][google.cloud.documentai.v1.DocumentProcessorService.GetProcessor] - method. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def train_processor_version(self, - request: Optional[Union[document_processor_service.TrainProcessorVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor_version: Optional[processor.ProcessorVersion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1.TrainProcessorVersionMetadata]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_train_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.TrainProcessorVersionRequest, dict]): - The request object. Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion] - method. - parent (str): - Required. The parent (project, location and processor) - to create the new version for. Format: - ``projects/{project}/locations/{location}/processors/{processor}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor_version (google.cloud.documentai_v1.types.ProcessorVersion): - Required. The processor version to be - created. - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1.types.TrainProcessorVersionResponse` The response for - [TrainProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, processor_version]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.TrainProcessorVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.TrainProcessorVersionRequest): - request = document_processor_service.TrainProcessorVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.train_processor_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.TrainProcessorVersionResponse, - metadata_type=document_processor_service.TrainProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def get_processor_version(self, - request: Optional[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_get_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetProcessorVersionRequest, dict]): - The request object. Request message for the - [GetProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion] - method. - 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, - pretrained by Google internally or - uptrained by the customer. A processor - can only have one default version at a - time. Its document-processing behavior - is defined by that 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsPager: - r"""Lists all versions of a processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_list_processor_versions(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ListProcessorVersionsRequest, dict]): - The request object. Request message for list all - processor versions belongs to a - processor. - parent (str): - Required. The parent (project, location and processor) - to list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorVersionsPager: - Response message for the - [ListProcessorVersions][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProcessorVersionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_delete_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DeleteProcessorVersionRequest, dict]): - The request object. Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_deploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DeployProcessorVersionRequest, dict]): - The request object. Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - 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 - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Undeploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.UndeployProcessorVersionRequest, dict]): - The request object. Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - 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 - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] - provided. 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 the - [CreateProcessor][google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized - backend service. If the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] - isn't available in that region, the creation fails. - 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][google.cloud.documentai.v1.Processor.type] - and - [Processor.display_name][google.cloud.documentai.v1.Processor.display_name] - to be set. Also, the - [Processor.kms_key_name][google.cloud.documentai.v1.Processor.kms_key_name] - field must be set if the processor is under CMEK. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_delete_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DeleteProcessorRequest, dict]): - The request object. Request message for the - [DeleteProcessor][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Enables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_enable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.EnableProcessorRequest, dict]): - The request object. Request message for the - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - 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 - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Disables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_disable_processor(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.DisableProcessorRequest, dict]): - The request object. Request message for the - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - 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 - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_set_default_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest, dict]): - The request object. Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - 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 the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_review_document(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1.Document() - inline_document.uri = "uri_value" - - request = documentai_v1.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ReviewDocumentRequest, dict]): - The request object. Request message for the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - method. - human_review_config (str): - Required. The resource name of the - [HumanReviewConfig][google.cloud.documentai.v1.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 the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # Done; return the response. - return response - - def evaluate_processor_version(self, - request: Optional[Union[document_processor_service.EvaluateProcessorVersionRequest, dict]] = None, - *, - processor_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.EvaluateProcessorVersionRequest, dict]): - The request object. Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - against the supplied documents. - processor_version (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to evaluate. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1.types.EvaluateProcessorVersionResponse` Response of the - [EvaluateProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([processor_version]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.EvaluateProcessorVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.EvaluateProcessorVersionRequest): - request = document_processor_service.EvaluateProcessorVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.evaluate_processor_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("processor_version", request.processor_version), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.EvaluateProcessorVersionResponse, - metadata_type=document_processor_service.EvaluateProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def get_evaluation(self, - request: Optional[Union[document_processor_service.GetEvaluationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation.Evaluation: - r"""Retrieves a specific evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_get_evaluation(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = client.get_evaluation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.GetEvaluationRequest, dict]): - The request object. Retrieves a specific Evaluation. - name (str): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1.Evaluation] to - get. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.types.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.GetEvaluationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.GetEvaluationRequest): - request = document_processor_service.GetEvaluationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_evaluation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_evaluations(self, - request: Optional[Union[document_processor_service.ListEvaluationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEvaluationsPager: - r"""Retrieves a set of evaluations for a given processor - version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1 - - def sample_list_evaluations(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1.types.ListEvaluationsRequest, dict]): - The request object. Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - parent (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to list evaluations for. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1.services.document_processor_service.pagers.ListEvaluationsPager: - The response from ListEvaluations. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.ListEvaluationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.ListEvaluationsRequest): - request = document_processor_service.ListEvaluationsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_evaluations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListEvaluationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentProcessorServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py deleted file mode 100644 index 7302ed92a4cf..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/pagers.py +++ /dev/null @@ -1,505 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor_type - - -class ListProcessorTypesPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListProcessorTypesResponse], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorTypesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListProcessorTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[processor_type.ProcessorType]: - for page in self.pages: - yield from page.processor_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorTypesAsyncPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorTypesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListProcessorTypesResponse]], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorTypesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListProcessorTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[processor_type.ProcessorType]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListProcessorsResponse], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListProcessorsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[processor.Processor]: - for page in self.pages: - yield from page.processors - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsAsyncPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListProcessorsResponse]], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListProcessorsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[processor.Processor]: - async def async_generator(): - async for page in self.pages: - for response in page.processors: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListProcessorVersionsResponse], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListProcessorVersionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[processor.ProcessorVersion]: - for page in self.pages: - yield from page.processor_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsAsyncPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListProcessorVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListProcessorVersionsResponse]], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListProcessorVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListProcessorVersionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[processor.ProcessorVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_versions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEvaluationsPager: - """A pager for iterating through ``list_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListEvaluationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``evaluations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEvaluations`` requests and continue to iterate - through the ``evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListEvaluationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListEvaluationsResponse], - request: document_processor_service.ListEvaluationsRequest, - response: document_processor_service.ListEvaluationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListEvaluationsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListEvaluationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListEvaluationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[evaluation.Evaluation]: - for page in self.pages: - yield from page.evaluations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEvaluationsAsyncPager: - """A pager for iterating through ``list_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1.types.ListEvaluationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``evaluations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEvaluations`` requests and continue to iterate - through the ``evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1.types.ListEvaluationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListEvaluationsResponse]], - request: document_processor_service.ListEvaluationsRequest, - response: document_processor_service.ListEvaluationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1.types.ListEvaluationsRequest): - The initial request object. - response (google.cloud.documentai_v1.types.ListEvaluationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListEvaluationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[evaluation.Evaluation]: - async def async_generator(): - async for page in self.pages: - for response in page.evaluations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py deleted file mode 100644 index ada8f5c0c0d9..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentProcessorServiceTransport -from .grpc import DocumentProcessorServiceGrpcTransport -from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .rest import DocumentProcessorServiceRestTransport -from .rest import DocumentProcessorServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] -_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentProcessorServiceRestTransport - -__all__ = ( - 'DocumentProcessorServiceTransport', - 'DocumentProcessorServiceGrpcTransport', - 'DocumentProcessorServiceGrpcAsyncIOTransport', - 'DocumentProcessorServiceRestTransport', - 'DocumentProcessorServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py deleted file mode 100644 index f03d05572850..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/base.py +++ /dev/null @@ -1,522 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.documentai_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentProcessorServiceTransport(abc.ABC): - """Abstract transport class for DocumentProcessorService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'documentai.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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 - - @property - def host(self): - return self._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=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.batch_process_documents: gapic_v1.method.wrap_method( - self.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.fetch_processor_types: gapic_v1.method.wrap_method( - self.fetch_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.list_processor_types: gapic_v1.method.wrap_method( - self.list_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.get_processor_type: gapic_v1.method.wrap_method( - self.get_processor_type, - default_timeout=None, - client_info=client_info, - ), - self.list_processors: gapic_v1.method.wrap_method( - self.list_processors, - default_timeout=None, - client_info=client_info, - ), - self.get_processor: gapic_v1.method.wrap_method( - self.get_processor, - default_timeout=None, - client_info=client_info, - ), - self.train_processor_version: gapic_v1.method.wrap_method( - self.train_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.get_processor_version: gapic_v1.method.wrap_method( - self.get_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.list_processor_versions: gapic_v1.method.wrap_method( - self.list_processor_versions, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor_version: gapic_v1.method.wrap_method( - self.delete_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.deploy_processor_version: gapic_v1.method.wrap_method( - self.deploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.undeploy_processor_version: gapic_v1.method.wrap_method( - self.undeploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.create_processor: gapic_v1.method.wrap_method( - self.create_processor, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor: gapic_v1.method.wrap_method( - self.delete_processor, - default_timeout=None, - client_info=client_info, - ), - self.enable_processor: gapic_v1.method.wrap_method( - self.enable_processor, - default_timeout=None, - client_info=client_info, - ), - self.disable_processor: gapic_v1.method.wrap_method( - self.disable_processor, - default_timeout=None, - client_info=client_info, - ), - self.set_default_processor_version: gapic_v1.method.wrap_method( - self.set_default_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.review_document: gapic_v1.method.wrap_method( - self.review_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.evaluate_processor_version: gapic_v1.method.wrap_method( - self.evaluate_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.get_evaluation: gapic_v1.method.wrap_method( - self.get_evaluation, - default_timeout=None, - client_info=client_info, - ), - self.list_evaluations: gapic_v1.method.wrap_method( - self.list_evaluations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - Union[ - document_processor_service.ProcessResponse, - Awaitable[document_processor_service.ProcessResponse] - ]]: - raise NotImplementedError() - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - Union[ - document_processor_service.FetchProcessorTypesResponse, - Awaitable[document_processor_service.FetchProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Union[ - document_processor_service.ListProcessorTypesResponse, - Awaitable[document_processor_service.ListProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Union[ - processor_type.ProcessorType, - Awaitable[processor_type.ProcessorType] - ]]: - raise NotImplementedError() - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Union[ - document_processor_service.ListProcessorsResponse, - Awaitable[document_processor_service.ListProcessorsResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Union[ - processor.Processor, - Awaitable[processor.Processor] - ]]: - raise NotImplementedError() - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Union[ - processor.ProcessorVersion, - Awaitable[processor.ProcessorVersion] - ]]: - raise NotImplementedError() - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Union[ - document_processor_service.ListProcessorVersionsResponse, - Awaitable[document_processor_service.ListProcessorVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Union[ - gcd_processor.Processor, - Awaitable[gcd_processor.Processor] - ]]: - raise NotImplementedError() - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - Union[ - evaluation.Evaluation, - Awaitable[evaluation.Evaluation] - ]]: - raise NotImplementedError() - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - Union[ - document_processor_service.ListEvaluationsResponse, - Awaitable[document_processor_service.ListEvaluationsResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentProcessorServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py deleted file mode 100644 index fffedf522783..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc.py +++ /dev/null @@ -1,947 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentProcessorServiceGrpcTransport(DocumentProcessorServiceTransport): - """gRPC backend transport for DocumentProcessorService. - - Service to call Document AI to process documents according to - the processor's definition. Processors are built using - state-of-the-art Google AI such as natural language, computer - vision, and translation to extract structured information from - unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessRequest], - ~.ProcessResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ProcessDocument', - request_serializer=document_processor_service.ProcessRequest.serialize, - response_deserializer=document_processor_service.ProcessResponse.deserialize, - ) - return self._stubs['process_document'] - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/BatchProcessDocuments', - request_serializer=document_processor_service.BatchProcessRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - r"""Return a callable for the fetch processor types method over gRPC. - - Fetches processor types. Note that we don't use - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - here, because it isn't paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - ~.FetchProcessorTypesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - ~.ListProcessorTypesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - ~.ProcessorType]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - ~.ListProcessorsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - ~.Processor]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - return self._stubs['get_processor'] - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the train processor version method over gRPC. - - Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1.TrainProcessorVersionMetadata]. - - Returns: - Callable[[~.TrainProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_processor_version' not in self._stubs: - self._stubs['train_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/TrainProcessorVersion', - request_serializer=document_processor_service.TrainProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_processor_version'] - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - ~.ProcessorVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - ~.ListProcessorVersionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] - provided. The processor will be at ``ENABLED`` state by default - after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - ~.Processor]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['review_document'] - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the evaluate processor version method over gRPC. - - Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - Returns: - Callable[[~.EvaluateProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'evaluate_processor_version' not in self._stubs: - self._stubs['evaluate_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/EvaluateProcessorVersion', - request_serializer=document_processor_service.EvaluateProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['evaluate_processor_version'] - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - evaluation.Evaluation]: - r"""Return a callable for the get evaluation method over gRPC. - - Retrieves a specific evaluation. - - Returns: - Callable[[~.GetEvaluationRequest], - ~.Evaluation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_evaluation' not in self._stubs: - self._stubs['get_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetEvaluation', - request_serializer=document_processor_service.GetEvaluationRequest.serialize, - response_deserializer=evaluation.Evaluation.deserialize, - ) - return self._stubs['get_evaluation'] - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - document_processor_service.ListEvaluationsResponse]: - r"""Return a callable for the list evaluations method over gRPC. - - Retrieves a set of evaluations for a given processor - version. - - Returns: - Callable[[~.ListEvaluationsRequest], - ~.ListEvaluationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_evaluations' not in self._stubs: - self._stubs['list_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListEvaluations', - request_serializer=document_processor_service.ListEvaluationsRequest.serialize, - response_deserializer=document_processor_service.ListEvaluationsResponse.deserialize, - ) - return self._stubs['list_evaluations'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentProcessorServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py deleted file mode 100644 index 961da248baeb..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,946 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # 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 Document AI to process documents according to - the processor's definition. Processors are built using - state-of-the-art Google AI such as natural language, computer - vision, and translation to extract structured information from - unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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 don't use - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - here, because it isn't paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - Awaitable[~.FetchProcessorTypesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Awaitable[document_processor_service.ListProcessorTypesResponse]]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - Awaitable[~.ListProcessorTypesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Awaitable[processor_type.ProcessorType]]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - Awaitable[~.ProcessorType]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Awaitable[document_processor_service.ListProcessorsResponse]]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - Awaitable[~.ListProcessorsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Awaitable[processor.Processor]]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - Awaitable[~.Processor]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - return self._stubs['get_processor'] - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the train processor version method over gRPC. - - Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1.TrainProcessorVersionMetadata]. - - Returns: - Callable[[~.TrainProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_processor_version' not in self._stubs: - self._stubs['train_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/TrainProcessorVersion', - request_serializer=document_processor_service.TrainProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_processor_version'] - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Awaitable[processor.ProcessorVersion]]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - Awaitable[~.ProcessorVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Awaitable[document_processor_service.ListProcessorVersionsResponse]]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - Awaitable[~.ListProcessorVersionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Awaitable[gcd_processor.Processor]]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] - provided. The processor will be at ``ENABLED`` state by default - after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - Awaitable[~.Processor]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1.Processor] that will be - used in - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['review_document'] - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the evaluate processor version method over gRPC. - - Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - Returns: - Callable[[~.EvaluateProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'evaluate_processor_version' not in self._stubs: - self._stubs['evaluate_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/EvaluateProcessorVersion', - request_serializer=document_processor_service.EvaluateProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['evaluate_processor_version'] - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - Awaitable[evaluation.Evaluation]]: - r"""Return a callable for the get evaluation method over gRPC. - - Retrieves a specific evaluation. - - Returns: - Callable[[~.GetEvaluationRequest], - Awaitable[~.Evaluation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_evaluation' not in self._stubs: - self._stubs['get_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/GetEvaluation', - request_serializer=document_processor_service.GetEvaluationRequest.serialize, - response_deserializer=evaluation.Evaluation.deserialize, - ) - return self._stubs['get_evaluation'] - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - Awaitable[document_processor_service.ListEvaluationsResponse]]: - r"""Return a callable for the list evaluations method over gRPC. - - Retrieves a set of evaluations for a given processor - version. - - Returns: - Callable[[~.ListEvaluationsRequest], - Awaitable[~.ListEvaluationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_evaluations' not in self._stubs: - self._stubs['list_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1.DocumentProcessorService/ListEvaluations', - request_serializer=document_processor_service.ListEvaluationsRequest.serialize, - response_deserializer=document_processor_service.ListEvaluationsResponse.deserialize, - ) - return self._stubs['list_evaluations'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'DocumentProcessorServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py deleted file mode 100644 index ba53b86688c9..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/services/document_processor_service/transports/rest.py +++ /dev/null @@ -1,3284 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentProcessorServiceRestInterceptor: - """Interceptor for DocumentProcessorService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DocumentProcessorServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentProcessorServiceInterceptor(DocumentProcessorServiceRestInterceptor): - def pre_batch_process_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_process_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_deploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_deploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_disable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_disable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_enable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_enable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_evaluate_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_evaluate_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_fetch_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_fetch_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_evaluation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_evaluation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_evaluations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_evaluations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processors(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processors(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_process_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_process_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_review_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_review_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_default_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_default_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_train_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_train_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undeploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undeploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentProcessorServiceRestTransport(interceptor=MyCustomDocumentProcessorServiceInterceptor()) - client = DocumentProcessorServiceClient(transport=transport) - - - """ - def pre_batch_process_documents(self, request: document_processor_service.BatchProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.BatchProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_batch_process_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_create_processor(self, request: document_processor_service.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.CreateProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_create_processor(self, response: gcd_processor.Processor) -> gcd_processor.Processor: - """Post-rpc interceptor for create_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor(self, request: document_processor_service.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor_version(self, request: document_processor_service.DeleteProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_deploy_processor_version(self, request: document_processor_service.DeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_deploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_disable_processor(self, request: document_processor_service.DisableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DisableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for disable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_disable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for disable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_enable_processor(self, request: document_processor_service.EnableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EnableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for enable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_enable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for enable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_evaluate_processor_version(self, request: document_processor_service.EvaluateProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EvaluateProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_evaluate_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_fetch_processor_types(self, request: document_processor_service.FetchProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.FetchProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_fetch_processor_types(self, response: document_processor_service.FetchProcessorTypesResponse) -> document_processor_service.FetchProcessorTypesResponse: - """Post-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_evaluation(self, request: document_processor_service.GetEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_evaluation(self, response: evaluation.Evaluation) -> evaluation.Evaluation: - """Post-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor(self, request: document_processor_service.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor(self, response: processor.Processor) -> processor.Processor: - """Post-rpc interceptor for get_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_type(self, request: document_processor_service.GetProcessorTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_type(self, response: processor_type.ProcessorType) -> processor_type.ProcessorType: - """Post-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_version(self, request: document_processor_service.GetProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_version(self, response: processor.ProcessorVersion) -> processor.ProcessorVersion: - """Post-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_evaluations(self, request: document_processor_service.ListEvaluationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_evaluations(self, response: document_processor_service.ListEvaluationsResponse) -> document_processor_service.ListEvaluationsResponse: - """Post-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processors(self, request: document_processor_service.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processors - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processors(self, response: document_processor_service.ListProcessorsResponse) -> document_processor_service.ListProcessorsResponse: - """Post-rpc interceptor for list_processors - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_types(self, request: document_processor_service.ListProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_types(self, response: document_processor_service.ListProcessorTypesResponse) -> document_processor_service.ListProcessorTypesResponse: - """Post-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_versions(self, request: document_processor_service.ListProcessorVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_versions(self, response: document_processor_service.ListProcessorVersionsResponse) -> document_processor_service.ListProcessorVersionsResponse: - """Post-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_process_document(self, request: document_processor_service.ProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for process_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_process_document(self, response: document_processor_service.ProcessResponse) -> document_processor_service.ProcessResponse: - """Post-rpc interceptor for process_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_review_document(self, request: document_processor_service.ReviewDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ReviewDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for review_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_review_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for review_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_set_default_processor_version(self, request: document_processor_service.SetDefaultProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.SetDefaultProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_set_default_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_train_processor_version(self, request: document_processor_service.TrainProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.TrainProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_train_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_undeploy_processor_version(self, request: document_processor_service.UndeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.UndeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_undeploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentProcessorServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentProcessorServiceRestInterceptor - - -class DocumentProcessorServiceRestTransport(DocumentProcessorServiceTransport): - """REST backend transport for DocumentProcessorService. - - Service to call Document AI to process documents according to - the processor's definition. Processors are built using - state-of-the-art Google AI such as natural language, computer - vision, and translation to extract structured information from - unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DocumentProcessorServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentProcessorServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchProcessDocuments(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("BatchProcessDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.BatchProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch process documents method over HTTP. - - Args: - request (~.document_processor_service.BatchProcessRequest): - The request object. Request message for - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:batchProcess', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:batchProcess', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_process_documents(request, metadata) - pb_request = document_processor_service.BatchProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_process_documents(resp) - return resp - - class _CreateProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("CreateProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.CreateProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_processor.Processor: - r"""Call the create processor method over HTTP. - - Args: - request (~.document_processor_service.CreateProcessorRequest): - The request object. Request message for the - [CreateProcessor][google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized - backend service. If the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] - isn't available in that region, the creation fails. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/processors', - 'body': 'processor', - }, - ] - request, metadata = self._interceptor.pre_create_processor(request, metadata) - pb_request = document_processor_service.CreateProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_processor.Processor() - pb_resp = gcd_processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_processor(resp) - return resp - - class _DeleteProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorRequest): - The request object. Request message for the - [DeleteProcessor][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor(request, metadata) - pb_request = document_processor_service.DeleteProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor(resp) - return resp - - class _DeleteProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor version method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorVersionRequest): - The request object. Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor_version(request, metadata) - pb_request = document_processor_service.DeleteProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor_version(resp) - return resp - - class _DeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the deploy processor version method over HTTP. - - Args: - request (~.document_processor_service.DeployProcessorVersionRequest): - The request object. Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_deploy_processor_version(request, metadata) - pb_request = document_processor_service.DeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_deploy_processor_version(resp) - return resp - - class _DisableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DisableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DisableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the disable processor method over HTTP. - - Args: - request (~.document_processor_service.DisableProcessorRequest): - The request object. Request message for the - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:disable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_disable_processor(request, metadata) - pb_request = document_processor_service.DisableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_disable_processor(resp) - return resp - - class _EnableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EnableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EnableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the enable processor method over HTTP. - - Args: - request (~.document_processor_service.EnableProcessorRequest): - The request object. Request message for the - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:enable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_enable_processor(request, metadata) - pb_request = document_processor_service.EnableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_enable_processor(resp) - return resp - - class _EvaluateProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EvaluateProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EvaluateProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the evaluate processor - version method over HTTP. - - Args: - request (~.document_processor_service.EvaluateProcessorVersionRequest): - The request object. Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - against the supplied documents. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_evaluate_processor_version(request, metadata) - pb_request = document_processor_service.EvaluateProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_evaluate_processor_version(resp) - return resp - - class _FetchProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("FetchProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.FetchProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Call the fetch processor types method over HTTP. - - Args: - request (~.document_processor_service.FetchProcessorTypesRequest): - The request object. Request message for the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.FetchProcessorTypesResponse: - Response message for the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}:fetchProcessorTypes', - }, - ] - request, metadata = self._interceptor.pre_fetch_processor_types(request, metadata) - pb_request = document_processor_service.FetchProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.FetchProcessorTypesResponse() - pb_resp = document_processor_service.FetchProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_processor_types(resp) - return resp - - class _GetEvaluation(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetEvaluation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetEvaluationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> evaluation.Evaluation: - r"""Call the get evaluation method over HTTP. - - Args: - request (~.document_processor_service.GetEvaluationRequest): - The request object. Retrieves a specific Evaluation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.evaluation.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_evaluation(request, metadata) - pb_request = document_processor_service.GetEvaluationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = evaluation.Evaluation() - pb_resp = evaluation.Evaluation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_evaluation(resp) - return resp - - class _GetProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.Processor: - r"""Call the get processor method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorRequest): - The request object. Request message for the - [GetProcessor][google.cloud.documentai.v1.DocumentProcessorService.GetProcessor] - 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: - ~.processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor(request, metadata) - pb_request = document_processor_service.GetProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.Processor() - pb_resp = processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor(resp) - return resp - - class _GetProcessorType(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor_type.ProcessorType: - r"""Call the get processor type method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorTypeRequest): - The request object. Request message for the - [GetProcessorType][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType] - 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: - ~.processor_type.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processorTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_type(request, metadata) - pb_request = document_processor_service.GetProcessorTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor_type.ProcessorType() - pb_resp = processor_type.ProcessorType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_type(resp) - return resp - - class _GetProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.ProcessorVersion: - r"""Call the get processor version method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorVersionRequest): - The request object. Request message for the - [GetProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion] - 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: - ~.processor.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pretrained by Google internally or - uptrained by the customer. A processor - can only have one default version at a - time. Its document-processing behavior - is defined by that version. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_version(request, metadata) - pb_request = document_processor_service.GetProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.ProcessorVersion() - pb_resp = processor.ProcessorVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_version(resp) - return resp - - class _ListEvaluations(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListEvaluations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListEvaluationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListEvaluationsResponse: - r"""Call the list evaluations method over HTTP. - - Args: - request (~.document_processor_service.ListEvaluationsRequest): - The request object. Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListEvaluationsResponse: - The response from ``ListEvaluations``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations', - }, - ] - request, metadata = self._interceptor.pre_list_evaluations(request, metadata) - pb_request = document_processor_service.ListEvaluationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListEvaluationsResponse() - pb_resp = document_processor_service.ListEvaluationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_evaluations(resp) - return resp - - class _ListProcessors(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessors") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorsResponse: - r"""Call the list processors method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorsRequest): - The request object. Request message for list all - processors belongs to a project. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListProcessorsResponse: - Response message for the - [ListProcessors][google.cloud.documentai.v1.DocumentProcessorService.ListProcessors] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/processors', - }, - ] - request, metadata = self._interceptor.pre_list_processors(request, metadata) - pb_request = document_processor_service.ListProcessorsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorsResponse() - pb_resp = document_processor_service.ListProcessorsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processors(resp) - return resp - - class _ListProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorTypesResponse: - r"""Call the list processor types method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorTypesRequest): - The request object. Request message for the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListProcessorTypesResponse: - Response message for the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/processorTypes', - }, - ] - request, metadata = self._interceptor.pre_list_processor_types(request, metadata) - pb_request = document_processor_service.ListProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorTypesResponse() - pb_resp = document_processor_service.ListProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_types(resp) - return resp - - class _ListProcessorVersions(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorVersionsResponse: - r"""Call the list processor versions method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorVersionsRequest): - The request object. Request message for list all - processor versions belongs to a - processor. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListProcessorVersionsResponse: - Response message for the - [ListProcessorVersions][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/processors/*}/processorVersions', - }, - ] - request, metadata = self._interceptor.pre_list_processor_versions(request, metadata) - pb_request = document_processor_service.ListProcessorVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorVersionsResponse() - pb_resp = document_processor_service.ListProcessorVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_versions(resp) - return resp - - class _ProcessDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ProcessDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ProcessResponse: - r"""Call the process document method over HTTP. - - Args: - request (~.document_processor_service.ProcessRequest): - The request object. Request message for the - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ProcessResponse: - Response message for the - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*}:process', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:process', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_process_document(request, metadata) - pb_request = document_processor_service.ProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ProcessResponse() - pb_resp = document_processor_service.ProcessResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_process_document(resp) - return resp - - class _ReviewDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ReviewDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ReviewDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the review document method over HTTP. - - Args: - request (~.document_processor_service.ReviewDocumentRequest): - The request object. Request message for the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_review_document(request, metadata) - pb_request = document_processor_service.ReviewDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_review_document(resp) - return resp - - class _SetDefaultProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("SetDefaultProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.SetDefaultProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the set default processor - version method over HTTP. - - Args: - request (~.document_processor_service.SetDefaultProcessorVersionRequest): - The request object. Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{processor=projects/*/locations/*/processors/*}:setDefaultProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_default_processor_version(request, metadata) - pb_request = document_processor_service.SetDefaultProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_default_processor_version(resp) - return resp - - class _TrainProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("TrainProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.TrainProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the train processor version method over HTTP. - - Args: - request (~.document_processor_service.TrainProcessorVersionRequest): - The request object. Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_train_processor_version(request, metadata) - pb_request = document_processor_service.TrainProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_train_processor_version(resp) - return resp - - class _UndeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("UndeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.UndeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the undeploy processor - version method over HTTP. - - Args: - request (~.document_processor_service.UndeployProcessorVersionRequest): - The request object. Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_undeploy_processor_version(request, metadata) - pb_request = document_processor_service.UndeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_undeploy_processor_version(resp) - return resp - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchProcessDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DisableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EnableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EvaluateProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._FetchProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - evaluation.Evaluation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - document_processor_service.ListEvaluationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ProcessDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ReviewDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetDefaultProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TrainProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UndeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentProcessorServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/__init__.py deleted file mode 100644 index e31c468157ee..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/__init__.py +++ /dev/null @@ -1,178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .barcode import ( - Barcode, -) -from .document import ( - Document, -) -from .document_io import ( - BatchDocumentsInputConfig, - DocumentOutputConfig, - GcsDocument, - GcsDocuments, - GcsPrefix, - OcrConfig, - RawDocument, -) -from .document_processor_service import ( - BatchProcessMetadata, - BatchProcessRequest, - BatchProcessResponse, - CreateProcessorRequest, - DeleteProcessorMetadata, - DeleteProcessorRequest, - DeleteProcessorVersionMetadata, - DeleteProcessorVersionRequest, - DeployProcessorVersionMetadata, - DeployProcessorVersionRequest, - DeployProcessorVersionResponse, - DisableProcessorMetadata, - DisableProcessorRequest, - DisableProcessorResponse, - EnableProcessorMetadata, - EnableProcessorRequest, - EnableProcessorResponse, - EvaluateProcessorVersionMetadata, - EvaluateProcessorVersionRequest, - EvaluateProcessorVersionResponse, - FetchProcessorTypesRequest, - FetchProcessorTypesResponse, - GetEvaluationRequest, - GetProcessorRequest, - GetProcessorTypeRequest, - GetProcessorVersionRequest, - HumanReviewStatus, - ListEvaluationsRequest, - ListEvaluationsResponse, - ListProcessorsRequest, - ListProcessorsResponse, - ListProcessorTypesRequest, - ListProcessorTypesResponse, - ListProcessorVersionsRequest, - ListProcessorVersionsResponse, - ProcessOptions, - ProcessRequest, - ProcessResponse, - ReviewDocumentOperationMetadata, - ReviewDocumentRequest, - ReviewDocumentResponse, - SetDefaultProcessorVersionMetadata, - SetDefaultProcessorVersionRequest, - SetDefaultProcessorVersionResponse, - TrainProcessorVersionMetadata, - TrainProcessorVersionRequest, - TrainProcessorVersionResponse, - UndeployProcessorVersionMetadata, - UndeployProcessorVersionRequest, - UndeployProcessorVersionResponse, -) -from .document_schema import ( - DocumentSchema, -) -from .evaluation import ( - Evaluation, - EvaluationReference, -) -from .geometry import ( - BoundingPoly, - NormalizedVertex, - Vertex, -) -from .operation_metadata import ( - CommonOperationMetadata, -) -from .processor import ( - Processor, - ProcessorVersion, - ProcessorVersionAlias, -) -from .processor_type import ( - ProcessorType, -) - -__all__ = ( - 'Barcode', - 'Document', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'OcrConfig', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessOptions', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorVersionAlias', - 'ProcessorType', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/barcode.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/barcode.py deleted file mode 100644 index a686695affc5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/barcode.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'Barcode', - }, -) - - -class Barcode(proto.Message): - r"""Encodes the detailed information of a barcode. - - Attributes: - format_ (str): - Format of a barcode. The supported formats are: - - - ``CODE_128``: Code 128 type. - - ``CODE_39``: Code 39 type. - - ``CODE_93``: Code 93 type. - - ``CODABAR``: Codabar type. - - ``DATA_MATRIX``: 2D Data Matrix type. - - ``ITF``: ITF type. - - ``EAN_13``: EAN-13 type. - - ``EAN_8``: EAN-8 type. - - ``QR_CODE``: 2D QR code type. - - ``UPC_A``: UPC-A type. - - ``UPC_E``: UPC-E type. - - ``PDF417``: PDF417 type. - - ``AZTEC``: 2D Aztec code type. - - ``DATABAR``: GS1 DataBar code type. - value_format (str): - Value format describes the format of the value that a - barcode encodes. The supported formats are: - - - ``CONTACT_INFO``: Contact information. - - ``EMAIL``: Email address. - - ``ISBN``: ISBN identifier. - - ``PHONE``: Phone number. - - ``PRODUCT``: Product. - - ``SMS``: SMS message. - - ``TEXT``: Text string. - - ``URL``: URL address. - - ``WIFI``: Wifi information. - - ``GEO``: Geo-localization. - - ``CALENDAR_EVENT``: Calendar event. - - ``DRIVER_LICENSE``: Driver's license. - raw_value (str): - Raw value encoded in the barcode. For example: - ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. - """ - - format_: str = proto.Field( - proto.STRING, - number=1, - ) - value_format: str = proto.Field( - proto.STRING, - number=2, - ) - raw_value: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document.py deleted file mode 100644 index adc56558a519..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document.py +++ /dev/null @@ -1,1830 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1.types import barcode as gcd_barcode -from google.cloud.documentai_v1.types import geometry -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import color_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import money_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'Document', - }, -) - - -class Document(proto.Message): - r"""Document represents the canonical document resource in - Document AI. It is an interchange format that provides insights - into documents and allows for collaboration between users and - Document AI to iterate and optimize for quality. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - uri (str): - Optional. Currently supports Google Cloud Storage URI of the - form ``gs://bucket_name/object_name``. Object versioning is - not supported. For more information, refer to `Google Cloud - Storage Request - URIs `__. - - 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 `media type (MIME - type) `__. - text (str): - Optional. UTF-8 encoded text in reading order - from the document. - text_styles (MutableSequence[google.cloud.documentai_v1.types.Document.Style]): - Styles for the - [Document.text][google.cloud.documentai.v1.Document.text]. - pages (MutableSequence[google.cloud.documentai_v1.types.Document.Page]): - Visual page layout for the - [Document][google.cloud.documentai.v1.Document]. - entities (MutableSequence[google.cloud.documentai_v1.types.Document.Entity]): - A list of entities detected on - [Document.text][google.cloud.documentai.v1.Document.text]. - For document shards, entities in this list may cross shard - boundaries. - entity_relations (MutableSequence[google.cloud.documentai_v1.types.Document.EntityRelation]): - Placeholder. Relationship among - [Document.entities][google.cloud.documentai.v1.Document.entities]. - text_changes (MutableSequence[google.cloud.documentai_v1.types.Document.TextChange]): - Placeholder. A list of text corrections made to - [Document.text][google.cloud.documentai.v1.Document.text]. - This is usually used for annotating corrections to OCR - mistakes. Text changes for a given revision may not overlap - with each other. - shard_info (google.cloud.documentai_v1.types.Document.ShardInfo): - Information about the sharding if this - document is sharded part of a larger document. - If the document is not sharded, this message is - not specified. - error (google.rpc.status_pb2.Status): - Any error that occurred while processing this - document. - revisions (MutableSequence[google.cloud.documentai_v1.types.Document.Revision]): - Placeholder. Revision history of this - document. - """ - - class ShardInfo(proto.Message): - r"""For a large document, sharding may be performed to produce - several document shards. Each document shard contains this field - to detail which shard it is. - - Attributes: - shard_index (int): - The 0-based index of this shard. - shard_count (int): - Total number of shards. - text_offset (int): - The index of the first character in - [Document.text][google.cloud.documentai.v1.Document.text] in - the overall document global text. - """ - - shard_index: int = proto.Field( - proto.INT64, - number=1, - ) - shard_count: int = proto.Field( - proto.INT64, - number=2, - ) - text_offset: int = proto.Field( - proto.INT64, - number=3, - ) - - class Style(proto.Message): - r"""Annotation for common text style attributes. This adheres to - CSS conventions as much as possible. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - color (google.type.color_pb2.Color): - Text color. - background_color (google.type.color_pb2.Color): - Text background color. - font_weight (str): - `Font - weight `__. - Possible values are ``normal``, ``bold``, ``bolder``, and - ``lighter``. - text_style (str): - `Text - style `__. - Possible values are ``normal``, ``italic``, and ``oblique``. - text_decoration (str): - `Text - decoration `__. - Follows CSS standard. - 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 (such as ``in``, - ``px``, and ``pt``). - """ - - size: float = proto.Field( - proto.FLOAT, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=2, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=3, - message=color_pb2.Color, - ) - font_weight: str = proto.Field( - proto.STRING, - number=4, - ) - text_style: str = proto.Field( - proto.STRING, - number=5, - ) - text_decoration: str = proto.Field( - proto.STRING, - number=6, - ) - font_size: 'Document.Style.FontSize' = proto.Field( - proto.MESSAGE, - number=7, - message='Document.Style.FontSize', - ) - font_family: str = proto.Field( - proto.STRING, - number=8, - ) - - class Page(proto.Message): - r"""A page in a [Document][google.cloud.documentai.v1.Document]. - - Attributes: - page_number (int): - 1-based index for current - [Page][google.cloud.documentai.v1.Document.Page] in a parent - [Document][google.cloud.documentai.v1.Document]. Useful when - a page is taken out of a - [Document][google.cloud.documentai.v1.Document] for - individual processing. - image (google.cloud.documentai_v1.types.Document.Page.Image): - Rendered image for this page. This image is - preprocessed to remove any skew, rotation, and - distortions such that the annotation bounding - boxes can be upright and axis-aligned. - transforms (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Matrix]): - Transformation matrices that were applied to the original - document image to produce - [Page.image][google.cloud.documentai.v1.Document.Page.image]. - dimension (google.cloud.documentai_v1.types.Document.Page.Dimension): - Physical dimension of the page. - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for the page. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - blocks (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Block]): - A list of visually detected text blocks on - the page. A block has a set of lines (collected - into paragraphs) that have a common line-spacing - and orientation. - paragraphs (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Paragraph]): - A list of visually detected text paragraphs - on the page. A collection of lines that a human - would perceive as a paragraph. - lines (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Line]): - A list of visually detected text lines on the - page. A collection of tokens that a human would - perceive as a line. - tokens (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Token]): - A list of visually detected tokens on the - page. - visual_elements (MutableSequence[google.cloud.documentai_v1.types.Document.Page.VisualElement]): - A list of detected non-text visual elements - e.g. checkbox, signature etc. on the page. - tables (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table]): - A list of visually detected tables on the - page. - form_fields (MutableSequence[google.cloud.documentai_v1.types.Document.Page.FormField]): - A list of visually detected form fields on - the page. - symbols (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Symbol]): - A list of visually detected symbols on the - page. - detected_barcodes (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedBarcode]): - A list of detected barcodes. - image_quality_scores (google.cloud.documentai_v1.types.Document.Page.ImageQualityScores): - Image quality scores. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this page. - """ - - class Dimension(proto.Message): - r"""Dimension for the page. - - Attributes: - width (float): - Page width. - height (float): - Page height. - unit (str): - Dimension unit. - """ - - width: float = proto.Field( - proto.FLOAT, - number=1, - ) - height: float = proto.Field( - proto.FLOAT, - number=2, - ) - unit: str = proto.Field( - proto.STRING, - number=3, - ) - - class Image(proto.Message): - r"""Rendered image contents for this page. - - Attributes: - content (bytes): - Raw byte content of the image. - mime_type (str): - Encoding `media type (MIME - type) `__ - for the image. - width (int): - Width of the image in pixels. - height (int): - Height of the image in pixels. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - width: int = proto.Field( - proto.INT32, - number=3, - ) - height: int = proto.Field( - proto.INT32, - number=4, - ) - - class Matrix(proto.Message): - r"""Representation for transformation matrix, intended to be - compatible and used with OpenCV format for image manipulation. - - Attributes: - rows (int): - Number of rows in the matrix. - cols (int): - Number of columns in the matrix. - type_ (int): - This encodes information about what data type the matrix - uses. For example, 0 (CV_8U) is an unsigned 8-bit image. For - the full list of OpenCV primitive data types, please refer - to - https://docs.opencv.org/4.3.0/d1/d1b/group__core__hal__interface.html - data (bytes): - The matrix data. - """ - - rows: int = proto.Field( - proto.INT32, - number=1, - ) - cols: int = proto.Field( - proto.INT32, - number=2, - ) - type_: int = proto.Field( - proto.INT32, - number=3, - ) - data: bytes = proto.Field( - proto.BYTES, - number=4, - ) - - class Layout(proto.Message): - r"""Visual element describing a layout unit on a page. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - confidence (float): - Confidence of the current - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - within context of the object this layout is for. e.g. - confidence can be for a single token, a table, a visual - element, etc. depending on context. Range ``[0, 1]``. - bounding_poly (google.cloud.documentai_v1.types.BoundingPoly): - The bounding polygon for the - [Layout][google.cloud.documentai.v1.Document.Page.Layout]. - orientation (google.cloud.documentai_v1.types.Document.Page.Layout.Orientation): - Detected orientation for the - [Layout][google.cloud.documentai.v1.Document.Page.Layout]. - """ - class Orientation(proto.Enum): - r"""Detected human reading orientation. - - Values: - ORIENTATION_UNSPECIFIED (0): - Unspecified orientation. - PAGE_UP (1): - Orientation is aligned with page up. - PAGE_RIGHT (2): - Orientation is aligned with page right. - Turn the head 90 degrees clockwise from upright - to read. - PAGE_DOWN (3): - Orientation is aligned with page down. - Turn the head 180 degrees from upright to read. - PAGE_LEFT (4): - Orientation is aligned with page left. - Turn the head 90 degrees counterclockwise from - upright to read. - """ - ORIENTATION_UNSPECIFIED = 0 - PAGE_UP = 1 - PAGE_RIGHT = 2 - PAGE_DOWN = 3 - PAGE_LEFT = 4 - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=3, - message=geometry.BoundingPoly, - ) - orientation: 'Document.Page.Layout.Orientation' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Page.Layout.Orientation', - ) - - class Block(proto.Message): - r"""A block has a set of lines (collected into paragraphs) that - have a common line-spacing and orientation. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Block][google.cloud.documentai.v1.Document.Page.Block]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Paragraph(proto.Message): - r"""A collection of lines that a human would perceive as a - paragraph. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [Paragraph][google.cloud.documentai.v1.Document.Page.Paragraph]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Line(proto.Message): - r"""A collection of tokens that a human would perceive as a line. - Does not cross column boundaries, can be horizontal, vertical, - etc. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Line][google.cloud.documentai.v1.Document.Page.Line]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Token(proto.Message): - r"""A detected token. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Token][google.cloud.documentai.v1.Document.Page.Token]. - detected_break (google.cloud.documentai_v1.types.Document.Page.Token.DetectedBreak): - Detected break at the end of a - [Token][google.cloud.documentai.v1.Document.Page.Token]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - style_info (google.cloud.documentai_v1.types.Document.Page.Token.StyleInfo): - Text style attributes. - """ - - class DetectedBreak(proto.Message): - r"""Detected break at the end of a - [Token][google.cloud.documentai.v1.Document.Page.Token]. - - Attributes: - type_ (google.cloud.documentai_v1.types.Document.Page.Token.DetectedBreak.Type): - Detected break type. - """ - class Type(proto.Enum): - r"""Enum to denote the type of break found. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified break type. - SPACE (1): - A single whitespace. - WIDE_SPACE (2): - A wider whitespace. - HYPHEN (3): - A hyphen that indicates that a token has been - split across lines. - """ - TYPE_UNSPECIFIED = 0 - SPACE = 1 - WIDE_SPACE = 2 - HYPHEN = 3 - - type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Document.Page.Token.DetectedBreak.Type', - ) - - class StyleInfo(proto.Message): - r"""Font and other text style attributes. - - Attributes: - font_size (int): - Font size in points (``1`` point is ``¹⁄₇₂`` inches). - pixel_font_size (float): - Font size in pixels, equal to *unrounded - [font_size][google.cloud.documentai.v1.Document.Page.Token.StyleInfo.font_size]* - - - *resolution* ÷ ``72.0``. - letter_spacing (float): - Letter spacing in points. - font_type (str): - Name or style of the font. - bold (bool): - Whether the text is bold (equivalent to - [font_weight][google.cloud.documentai.v1.Document.Page.Token.StyleInfo.font_weight] - is at least ``700``). - italic (bool): - Whether the text is italic. - underlined (bool): - Whether the text is underlined. - strikeout (bool): - Whether the text is strikethrough. - subscript (bool): - Whether the text is a subscript. - superscript (bool): - Whether the text is a superscript. - smallcaps (bool): - Whether the text is in small caps. - font_weight (int): - TrueType weight on a scale ``100`` (thin) to ``1000`` - (ultra-heavy). Normal is ``400``, bold is ``700``. - handwritten (bool): - Whether the text is handwritten. - text_color (google.type.color_pb2.Color): - Color of the text. - background_color (google.type.color_pb2.Color): - Color of the background. - """ - - font_size: int = proto.Field( - proto.INT32, - number=1, - ) - pixel_font_size: float = proto.Field( - proto.DOUBLE, - number=2, - ) - letter_spacing: float = proto.Field( - proto.DOUBLE, - number=3, - ) - font_type: str = proto.Field( - proto.STRING, - number=4, - ) - bold: bool = proto.Field( - proto.BOOL, - number=5, - ) - italic: bool = proto.Field( - proto.BOOL, - number=6, - ) - underlined: bool = proto.Field( - proto.BOOL, - number=7, - ) - strikeout: bool = proto.Field( - proto.BOOL, - number=8, - ) - subscript: bool = proto.Field( - proto.BOOL, - number=9, - ) - superscript: bool = proto.Field( - proto.BOOL, - number=10, - ) - smallcaps: bool = proto.Field( - proto.BOOL, - number=11, - ) - font_weight: int = proto.Field( - proto.INT32, - number=12, - ) - handwritten: bool = proto.Field( - proto.BOOL, - number=13, - ) - text_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=14, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=15, - message=color_pb2.Color, - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Token.DetectedBreak', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=4, - message='Document.Provenance', - ) - style_info: 'Document.Page.Token.StyleInfo' = proto.Field( - proto.MESSAGE, - number=5, - message='Document.Page.Token.StyleInfo', - ) - - class Symbol(proto.Message): - r"""A detected symbol. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [Symbol][google.cloud.documentai.v1.Document.Page.Symbol]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class VisualElement(proto.Message): - r"""Detected non-text visual elements e.g. checkbox, signature - etc. on the page. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [VisualElement][google.cloud.documentai.v1.Document.Page.VisualElement]. - type_ (str): - Type of the - [VisualElement][google.cloud.documentai.v1.Document.Page.VisualElement]. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - - class Table(proto.Message): - r"""A table representation similar to HTML table structure. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for [Table][google.cloud.documentai.v1.Document.Page.Table]. - header_rows (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): - Header rows of the table. - body_rows (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableRow]): - Body rows of the table. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this table. - """ - - class TableRow(proto.Message): - r"""A row of table cells. - - Attributes: - cells (MutableSequence[google.cloud.documentai_v1.types.Document.Page.Table.TableCell]): - Cells that make up this row. - """ - - cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.Page.Table.TableCell', - ) - - class TableCell(proto.Message): - r"""A cell representation inside the table. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [TableCell][google.cloud.documentai.v1.Document.Page.Table.TableCell]. - row_span (int): - How many rows this cell spans. - col_span (int): - How many columns this cell spans. - detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - row_span: int = proto.Field( - proto.INT32, - number=2, - ) - col_span: int = proto.Field( - proto.INT32, - number=3, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.Table.TableRow', - ) - body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.Table.TableRow', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=5, - message='Document.Provenance', - ) - - class FormField(proto.Message): - r"""A form field detected on the page. - - Attributes: - field_name (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1.Document.Page.FormField] - name. e.g. ``Address``, ``Email``, ``Grand total``, - ``Phone number``, etc. - field_value (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1.Document.Page.FormField] - value. - name_detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages for name - together with confidence. - value_detected_languages (MutableSequence[google.cloud.documentai_v1.types.Document.Page.DetectedLanguage]): - A list of detected languages for value - together with confidence. - value_type (str): - If the value is non-textual, this field represents the type. - Current valid values are: - - - blank (this indicates the ``field_value`` is normal text) - - ``unfilled_checkbox`` - - ``filled_checkbox`` - corrected_key_text (str): - Created for Labeling UI to export key text. If corrections - were made to the text identified by the - ``field_name.text_anchor``, this field will contain the - correction. - corrected_value_text (str): - Created for Labeling UI to export value text. If corrections - were made to the text identified by the - ``field_value.text_anchor``, this field will contain the - correction. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - The history of this annotation. - """ - - field_name: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - field_value: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Layout', - ) - name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - value_type: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_key_text: str = proto.Field( - proto.STRING, - number=6, - ) - corrected_value_text: str = proto.Field( - proto.STRING, - number=7, - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=8, - message='Document.Provenance', - ) - - class DetectedBarcode(proto.Message): - r"""A detected barcode. - - Attributes: - layout (google.cloud.documentai_v1.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1.Document.Page.Layout] - for - [DetectedBarcode][google.cloud.documentai.v1.Document.Page.DetectedBarcode]. - barcode (google.cloud.documentai_v1.types.Barcode): - Detailed barcode information of the - [DetectedBarcode][google.cloud.documentai.v1.Document.Page.DetectedBarcode]. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - barcode: gcd_barcode.Barcode = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_barcode.Barcode, - ) - - class DetectedLanguage(proto.Message): - r"""Detected language for a structural component. - - Attributes: - language_code (str): - The `BCP-47 language - code `__, - such as ``en-US`` or ``sr-Latn``. - confidence (float): - Confidence of detected language. Range ``[0, 1]``. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - class ImageQualityScores(proto.Message): - r"""Image quality scores for the page image. - - Attributes: - quality_score (float): - The overall quality score. Range ``[0, 1]`` where ``1`` is - perfect quality. - detected_defects (MutableSequence[google.cloud.documentai_v1.types.Document.Page.ImageQualityScores.DetectedDefect]): - A list of detected defects. - """ - - class DetectedDefect(proto.Message): - r"""Image Quality Defects - - Attributes: - type_ (str): - Name of the defect type. Supported values are: - - - ``quality/defect_blurry`` - - ``quality/defect_noisy`` - - ``quality/defect_dark`` - - ``quality/defect_faint`` - - ``quality/defect_text_too_small`` - - ``quality/defect_document_cutoff`` - - ``quality/defect_text_cutoff`` - - ``quality/defect_glare`` - confidence (float): - Confidence of detected defect. Range ``[0, 1]`` where ``1`` - indicates strong confidence that the defect exists. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - quality_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - detected_defects: MutableSequence['Document.Page.ImageQualityScores.DetectedDefect'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.ImageQualityScores.DetectedDefect', - ) - - page_number: int = proto.Field( - proto.INT32, - number=1, - ) - image: 'Document.Page.Image' = proto.Field( - proto.MESSAGE, - number=13, - message='Document.Page.Image', - ) - transforms: MutableSequence['Document.Page.Matrix'] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='Document.Page.Matrix', - ) - dimension: 'Document.Page.Dimension' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Dimension', - ) - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Document.Page.Block', - ) - paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Document.Page.Paragraph', - ) - lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Document.Page.Line', - ) - tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='Document.Page.Token', - ) - visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Document.Page.VisualElement', - ) - tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Page.Table', - ) - form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='Document.Page.FormField', - ) - symbols: MutableSequence['Document.Page.Symbol'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='Document.Page.Symbol', - ) - detected_barcodes: MutableSequence['Document.Page.DetectedBarcode'] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message='Document.Page.DetectedBarcode', - ) - image_quality_scores: 'Document.Page.ImageQualityScores' = proto.Field( - proto.MESSAGE, - number=17, - message='Document.Page.ImageQualityScores', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=16, - message='Document.Provenance', - ) - - class Entity(proto.Message): - r"""An entity that could be a phrase in the text or a property - that belongs to the document. It is a known entity type, such as - a person, an organization, or location. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Optional. Provenance of the entity. Text anchor indexing - into the - [Document.text][google.cloud.documentai.v1.Document.text]. - type_ (str): - Required. Entity type from a schema e.g. ``Address``. - mention_text (str): - Optional. Text value of the entity e.g. - ``1600 Amphitheatre Pkwy``. - mention_id (str): - Optional. Deprecated. Use ``id`` field instead. - confidence (float): - Optional. Confidence of detected Schema entity. Range - ``[0, 1]``. - page_anchor (google.cloud.documentai_v1.types.Document.PageAnchor): - Optional. Represents the provenance of this - entity wrt. the location on the page where it - was found. - id (str): - Optional. Canonical id. This will be a unique - value in the entity list for this document. - normalized_value (google.cloud.documentai_v1.types.Document.Entity.NormalizedValue): - Optional. Normalized entity value. Absent if - the extracted value could not be converted or - the type (e.g. address) is not supported for - certain parsers. This field is also only - populated for certain supported document types. - properties (MutableSequence[google.cloud.documentai_v1.types.Document.Entity]): - Optional. Entities can be nested to form a - hierarchical data structure representing the - content in the document. - provenance (google.cloud.documentai_v1.types.Document.Provenance): - Optional. The history of this annotation. - redacted (bool): - Optional. Whether the entity will be redacted - for de-identification purposes. - """ - - class NormalizedValue(proto.Message): - r"""Parsed and normalized entity value. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - money_value (google.type.money_pb2.Money): - Money value. See also: - - https://github.com/googleapis/googleapis/blob/master/google/type/money.proto - - This field is a member of `oneof`_ ``structured_value``. - date_value (google.type.date_pb2.Date): - Date value. Includes year, month, day. See - also: - https://github.com/googleapis/googleapis/blob/master/google/type/date.proto - - This field is a member of `oneof`_ ``structured_value``. - datetime_value (google.type.datetime_pb2.DateTime): - DateTime value. Includes date, time, and - timezone. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/datetime.proto - - This field is a member of `oneof`_ ``structured_value``. - address_value (google.type.postal_address_pb2.PostalAddress): - Postal address. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/postal_address.proto - - This field is a member of `oneof`_ ``structured_value``. - boolean_value (bool): - Boolean value. Can be used for entities with - binary values, or for checkboxes. - - This field is a member of `oneof`_ ``structured_value``. - integer_value (int): - Integer value. - - This field is a member of `oneof`_ ``structured_value``. - float_value (float): - Float value. - - This field is a member of `oneof`_ ``structured_value``. - text (str): - Optional. An optional field to store a normalized string. - For some entity types, one of respective - ``structured_value`` fields may also be populated. Also not - all the types of ``structured_value`` will be normalized. - For example, some processors may not generate ``float`` or - ``integer`` normalized text by default. - - Below are sample formats mapped to structured values. - - - Money/Currency type (``money_value``) is in the ISO 4217 - text format. - - Date type (``date_value``) is in the ISO 8601 text - format. - - Datetime type (``datetime_value``) is in the ISO 8601 - text format. - """ - - money_value: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - oneof='structured_value', - message=money_pb2.Money, - ) - date_value: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - oneof='structured_value', - message=date_pb2.Date, - ) - datetime_value: datetime_pb2.DateTime = proto.Field( - proto.MESSAGE, - number=4, - oneof='structured_value', - message=datetime_pb2.DateTime, - ) - address_value: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=5, - oneof='structured_value', - message=postal_address_pb2.PostalAddress, - ) - boolean_value: bool = proto.Field( - proto.BOOL, - number=6, - oneof='structured_value', - ) - integer_value: int = proto.Field( - proto.INT32, - number=7, - oneof='structured_value', - ) - float_value: float = proto.Field( - proto.FLOAT, - number=8, - oneof='structured_value', - ) - text: str = proto.Field( - proto.STRING, - number=1, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - mention_text: str = proto.Field( - proto.STRING, - number=3, - ) - mention_id: str = proto.Field( - proto.STRING, - number=4, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - page_anchor: 'Document.PageAnchor' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.PageAnchor', - ) - id: str = proto.Field( - proto.STRING, - number=7, - ) - normalized_value: 'Document.Entity.NormalizedValue' = proto.Field( - proto.MESSAGE, - number=9, - message='Document.Entity.NormalizedValue', - ) - properties: MutableSequence['Document.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Entity', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=11, - message='Document.Provenance', - ) - redacted: bool = proto.Field( - proto.BOOL, - number=12, - ) - - class EntityRelation(proto.Message): - r"""Relationship between - [Entities][google.cloud.documentai.v1.Document.Entity]. - - Attributes: - subject_id (str): - Subject entity id. - object_id (str): - Object entity id. - relation (str): - Relationship description. - """ - - subject_id: str = proto.Field( - proto.STRING, - number=1, - ) - object_id: str = proto.Field( - proto.STRING, - number=2, - ) - relation: str = proto.Field( - proto.STRING, - number=3, - ) - - class TextAnchor(proto.Message): - r"""Text reference indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - - Attributes: - text_segments (MutableSequence[google.cloud.documentai_v1.types.Document.TextAnchor.TextSegment]): - The text segments from the - [Document.text][google.cloud.documentai.v1.Document.text]. - content (str): - Contains the content of the text span so that users do not - have to look it up in the text_segments. It is always - populated for formFields. - """ - - class TextSegment(proto.Message): - r"""A text segment in the - [Document.text][google.cloud.documentai.v1.Document.text]. The - indices may be out of bounds which indicate that the text extends - into another document shard for large sharded documents. See - [ShardInfo.text_offset][google.cloud.documentai.v1.Document.ShardInfo.text_offset] - - Attributes: - start_index (int): - [TextSegment][google.cloud.documentai.v1.Document.TextAnchor.TextSegment] - start UTF-8 char index in the - [Document.text][google.cloud.documentai.v1.Document.text]. - end_index (int): - [TextSegment][google.cloud.documentai.v1.Document.TextAnchor.TextSegment] - half open end UTF-8 char index in the - [Document.text][google.cloud.documentai.v1.Document.text]. - """ - - start_index: int = proto.Field( - proto.INT64, - number=1, - ) - end_index: int = proto.Field( - proto.INT64, - number=2, - ) - - text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.TextAnchor.TextSegment', - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class PageAnchor(proto.Message): - r"""Referencing the visual context of the entity in the - [Document.pages][google.cloud.documentai.v1.Document.pages]. Page - anchors can be cross-page, consist of multiple bounding polygons and - optionally reference specific layout element types. - - Attributes: - page_refs (MutableSequence[google.cloud.documentai_v1.types.Document.PageAnchor.PageRef]): - One or more references to visual page - elements - """ - - class PageRef(proto.Message): - r"""Represents a weak reference to a page element within a - document. - - Attributes: - page (int): - Required. Index into the - [Document.pages][google.cloud.documentai.v1.Document.pages] - element, for example using - ``[Document.pages][page_refs.page]`` to locate the related - page element. This field is skipped when its value is the - default ``0``. See - https://developers.google.com/protocol-buffers/docs/proto3#json. - layout_type (google.cloud.documentai_v1.types.Document.PageAnchor.PageRef.LayoutType): - Optional. The type of the layout element that - is being referenced if any. - layout_id (str): - Optional. Deprecated. Use - [PageRef.bounding_poly][google.cloud.documentai.v1.Document.PageAnchor.PageRef.bounding_poly] - instead. - bounding_poly (google.cloud.documentai_v1.types.BoundingPoly): - Optional. Identifies the bounding polygon of a layout - element on the page. If ``layout_type`` is set, the bounding - polygon must be exactly the same to the layout element it's - referring to. - confidence (float): - Optional. Confidence of detected page element, if - applicable. Range ``[0, 1]``. - """ - class LayoutType(proto.Enum): - r"""The type of layout that is being referenced. - - Values: - LAYOUT_TYPE_UNSPECIFIED (0): - Layout Unspecified. - BLOCK (1): - References a - [Page.blocks][google.cloud.documentai.v1.Document.Page.blocks] - element. - PARAGRAPH (2): - References a - [Page.paragraphs][google.cloud.documentai.v1.Document.Page.paragraphs] - element. - LINE (3): - References a - [Page.lines][google.cloud.documentai.v1.Document.Page.lines] - element. - TOKEN (4): - References a - [Page.tokens][google.cloud.documentai.v1.Document.Page.tokens] - element. - VISUAL_ELEMENT (5): - References a - [Page.visual_elements][google.cloud.documentai.v1.Document.Page.visual_elements] - element. - TABLE (6): - Refrrences a - [Page.tables][google.cloud.documentai.v1.Document.Page.tables] - element. - FORM_FIELD (7): - References a - [Page.form_fields][google.cloud.documentai.v1.Document.Page.form_fields] - element. - """ - LAYOUT_TYPE_UNSPECIFIED = 0 - BLOCK = 1 - PARAGRAPH = 2 - LINE = 3 - TOKEN = 4 - VISUAL_ELEMENT = 5 - TABLE = 6 - FORM_FIELD = 7 - - page: int = proto.Field( - proto.INT64, - number=1, - ) - layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( - proto.ENUM, - number=2, - enum='Document.PageAnchor.PageRef.LayoutType', - ) - layout_id: str = proto.Field( - proto.STRING, - number=3, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=4, - message=geometry.BoundingPoly, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - - page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.PageAnchor.PageRef', - ) - - class Provenance(proto.Message): - r"""Structure to identify provenance relationships between - annotations in different revisions. - - Attributes: - revision (int): - The index of the revision that produced this - element. - id (int): - The Id of this operation. Needs to be unique - within the scope of the revision. - parents (MutableSequence[google.cloud.documentai_v1.types.Document.Provenance.Parent]): - References to the original elements that are - replaced. - type_ (google.cloud.documentai_v1.types.Document.Provenance.OperationType): - The type of provenance operation. - """ - class OperationType(proto.Enum): - r"""If a processor or agent does an explicit operation on - existing elements. - - Values: - OPERATION_TYPE_UNSPECIFIED (0): - Operation type unspecified. If no operation is specified a - provenance entry is simply used to match against a - ``parent``. - ADD (1): - Add an element. - REMOVE (2): - Remove an element identified by ``parent``. - UPDATE (7): - Updates any fields within the given - provenance scope of the message. It overwrites - the fields rather than replacing them. Use this - when you want to update a field value of an - entity without also updating all the child - properties. - REPLACE (3): - Currently unused. Replace an element identified by - ``parent``. - EVAL_REQUESTED (4): - Deprecated. Request human review for the element identified - by ``parent``. - EVAL_APPROVED (5): - Deprecated. Element is reviewed and approved - at human review, confidence will be set to 1.0. - EVAL_SKIPPED (6): - Deprecated. Element is skipped in the - validation process. - """ - OPERATION_TYPE_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - UPDATE = 7 - REPLACE = 3 - EVAL_REQUESTED = 4 - EVAL_APPROVED = 5 - EVAL_SKIPPED = 6 - - class Parent(proto.Message): - r"""The parent element the current element is based on. Used for - referencing/aligning, removal and replacement operations. - - Attributes: - revision (int): - The index of the index into current revision's parent_ids - list. - index (int): - The index of the parent item in the - corresponding item list (eg. list of entities, - properties within entities, etc.) in the parent - revision. - id (int): - The id of the parent provenance. - """ - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - index: int = proto.Field( - proto.INT32, - number=3, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - parents: MutableSequence['Document.Provenance.Parent'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance.Parent', - ) - type_: 'Document.Provenance.OperationType' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Provenance.OperationType', - ) - - class Revision(proto.Message): - r"""Contains past or forward revisions of this document. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - agent (str): - If the change was made by a person specify - the name or id of that person. - - This field is a member of `oneof`_ ``source``. - processor (str): - If the annotation was made by processor - identify the processor by its resource name. - - This field is a member of `oneof`_ ``source``. - id (str): - Id of the revision, internally generated by - doc proto storage. Unique within the context of - the document. - parent (MutableSequence[int]): - The revisions that this revision is based on. This can - include one or more parent (when documents are merged.) This - field represents the index into the ``revisions`` field. - parent_ids (MutableSequence[str]): - The revisions that this revision is based on. Must include - all the ids that have anything to do with this revision - - eg. there are ``provenance.parent.revision`` fields that - index into this field. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the revision was created, - internally generated by doc proto storage at the - time of create. - human_review (google.cloud.documentai_v1.types.Document.Revision.HumanReview): - Human Review information of this revision. - """ - - class HumanReview(proto.Message): - r"""Human Review information of the document. - - Attributes: - state (str): - Human review state. e.g. ``requested``, ``succeeded``, - ``rejected``. - state_message (str): - A message providing more details about the current state of - processing. For example, the rejection reason when the state - is ``rejected``. - """ - - state: str = proto.Field( - proto.STRING, - number=1, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - - agent: str = proto.Field( - proto.STRING, - number=4, - oneof='source', - ) - processor: str = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - id: str = proto.Field( - proto.STRING, - number=1, - ) - parent: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=2, - ) - parent_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - human_review: 'Document.Revision.HumanReview' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.Revision.HumanReview', - ) - - class TextChange(proto.Message): - r"""This message is used for text changes aka. OCR corrections. - - Attributes: - text_anchor (google.cloud.documentai_v1.types.Document.TextAnchor): - Provenance of the correction. Text anchor indexing into the - [Document.text][google.cloud.documentai.v1.Document.text]. - There can only be a single ``TextAnchor.text_segments`` - element. If the start and end index of the text segment are - the same, the text change is inserted before that index. - changed_text (str): - The text that replaces the text identified in the - ``text_anchor``. - provenance (MutableSequence[google.cloud.documentai_v1.types.Document.Provenance]): - The history of this annotation. - """ - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - changed_text: str = proto.Field( - proto.STRING, - number=2, - ) - provenance: MutableSequence['Document.Provenance'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - text: str = proto.Field( - proto.STRING, - number=4, - ) - text_styles: MutableSequence[Style] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Style, - ) - pages: MutableSequence[Page] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Page, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Entity, - ) - entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=EntityRelation, - ) - text_changes: MutableSequence[TextChange] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=TextChange, - ) - shard_info: ShardInfo = proto.Field( - proto.MESSAGE, - number=9, - message=ShardInfo, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - revisions: MutableSequence[Revision] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Revision, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_io.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_io.py deleted file mode 100644 index 55f8e8688deb..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_io.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'RawDocument', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'OcrConfig', - }, -) - - -class RawDocument(proto.Message): - r"""Payload message of raw document content (bytes). - - Attributes: - content (bytes): - Inline document content. - mime_type (str): - An IANA MIME type (RFC6838) indicating the nature and format - of the - [content][google.cloud.documentai.v1.RawDocument.content]. - display_name (str): - The display name of the document, it supports all Unicode - characters except the following: ``*``, ``?``, ``[``, ``]``, - ``%``, ``{``, ``}``,\ ``'``, ``\"``, ``,`` ``~``, ``=`` and - ``:`` are reserved. If not specified, a default ID is - generated. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GcsDocument(proto.Message): - r"""Specifies a document stored on Cloud Storage. - - Attributes: - gcs_uri (str): - The Cloud Storage object uri. - mime_type (str): - An IANA MIME type (RFC6838) of the content. - """ - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GcsDocuments(proto.Message): - r"""Specifies a set of documents on Cloud Storage. - - Attributes: - documents (MutableSequence[google.cloud.documentai_v1.types.GcsDocument]): - The list of documents. - """ - - documents: MutableSequence['GcsDocument'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GcsDocument', - ) - - -class GcsPrefix(proto.Message): - r"""Specifies all documents on Cloud Storage with a common - prefix. - - Attributes: - gcs_uri_prefix (str): - The URI prefix. - """ - - gcs_uri_prefix: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchDocumentsInputConfig(proto.Message): - r"""The common config to specify a set of documents used as - input. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (google.cloud.documentai_v1.types.GcsPrefix): - The set of documents that match the specified Cloud Storage - ``gcs_prefix``. - - This field is a member of `oneof`_ ``source``. - gcs_documents (google.cloud.documentai_v1.types.GcsDocuments): - The set of documents individually specified - on Cloud Storage. - - This field is a member of `oneof`_ ``source``. - """ - - gcs_prefix: 'GcsPrefix' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsPrefix', - ) - gcs_documents: 'GcsDocuments' = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsDocuments', - ) - - -class DocumentOutputConfig(proto.Message): - r"""Config that controls the output of documents. All documents - will be written as a JSON file. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_output_config (google.cloud.documentai_v1.types.DocumentOutputConfig.GcsOutputConfig): - Output config to write the results to Cloud - Storage. - - This field is a member of `oneof`_ ``destination``. - """ - - class GcsOutputConfig(proto.Message): - r"""The configuration used when outputting documents. - - Attributes: - gcs_uri (str): - The Cloud Storage uri (a directory) of the - output. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies which fields to include in the output documents. - Only supports top level document and pages field so it must - be in the form of ``{document_field_name}`` or - ``pages.{page_field_name}``. - sharding_config (google.cloud.documentai_v1.types.DocumentOutputConfig.GcsOutputConfig.ShardingConfig): - Specifies the sharding config for the output - document. - """ - - class ShardingConfig(proto.Message): - r"""The sharding config for the output document. - - Attributes: - pages_per_shard (int): - The number of pages per shard. - pages_overlap (int): - The number of overlapping pages between - consecutive shards. - """ - - pages_per_shard: int = proto.Field( - proto.INT32, - number=1, - ) - pages_overlap: int = proto.Field( - proto.INT32, - number=2, - ) - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - sharding_config: 'DocumentOutputConfig.GcsOutputConfig.ShardingConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='DocumentOutputConfig.GcsOutputConfig.ShardingConfig', - ) - - gcs_output_config: GcsOutputConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message=GcsOutputConfig, - ) - - -class OcrConfig(proto.Message): - r"""Config for Document OCR. - - Attributes: - hints (google.cloud.documentai_v1.types.OcrConfig.Hints): - Hints for the OCR model. - enable_native_pdf_parsing (bool): - Enables special handling for PDFs with - existing text information. Results in better - text extraction quality in such PDF inputs. - enable_image_quality_scores (bool): - Enables intelligent document quality scores - after OCR. Can help with diagnosing why OCR - responses are of poor quality for a given input. - Adds additional latency comparable to regular - OCR to the process call. - advanced_ocr_options (MutableSequence[str]): - A list of advanced OCR options to further fine-tune OCR - behavior. Current valid values are: - - - ``legacy_layout``: a heuristics layout detection - algorithm, which serves as an alternative to the current - ML-based layout detection algorithm. Customers can choose - the best suitable layout algorithm based on their - situation. - enable_symbol (bool): - Includes symbol level OCR information if set - to true. - compute_style_info (bool): - Turn on font identification model and return font style - information. Deprecated, use - [PremiumFeatures.compute_style_info][google.cloud.documentai.v1.OcrConfig.PremiumFeatures.compute_style_info] - instead. - disable_character_boxes_detection (bool): - Turn off character box detector in OCR - engine. Character box detection is enabled by - default in OCR 2.0 (and later) processors. - premium_features (google.cloud.documentai_v1.types.OcrConfig.PremiumFeatures): - Configurations for premium OCR features. - """ - - class Hints(proto.Message): - r"""Hints for OCR Engine - - Attributes: - language_hints (MutableSequence[str]): - List of BCP-47 language codes to use for OCR. - In most cases, not specifying it yields the best - results since it enables automatic language - detection. For languages based on the Latin - alphabet, setting 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). - """ - - language_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class PremiumFeatures(proto.Message): - r"""Configurations for premium OCR features. - - Attributes: - enable_selection_mark_detection (bool): - Turn on selection mark detector in OCR - engine. Only available in OCR 2.0 (and later) - processors. - compute_style_info (bool): - Turn on font identification model and return - font style information. - enable_math_ocr (bool): - Turn on the model that can extract LaTeX math - formulas. - """ - - enable_selection_mark_detection: bool = proto.Field( - proto.BOOL, - number=3, - ) - compute_style_info: bool = proto.Field( - proto.BOOL, - number=4, - ) - enable_math_ocr: bool = proto.Field( - proto.BOOL, - number=5, - ) - - hints: Hints = proto.Field( - proto.MESSAGE, - number=2, - message=Hints, - ) - enable_native_pdf_parsing: bool = proto.Field( - proto.BOOL, - number=3, - ) - enable_image_quality_scores: bool = proto.Field( - proto.BOOL, - number=4, - ) - advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - enable_symbol: bool = proto.Field( - proto.BOOL, - number=6, - ) - compute_style_info: bool = proto.Field( - proto.BOOL, - number=8, - ) - disable_character_boxes_detection: bool = proto.Field( - proto.BOOL, - number=10, - ) - premium_features: PremiumFeatures = proto.Field( - proto.MESSAGE, - number=11, - message=PremiumFeatures, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_processor_service.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_processor_service.py deleted file mode 100644 index 6f90319ff877..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_processor_service.py +++ /dev/null @@ -1,1624 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1.types import document as gcd_document -from google.cloud.documentai_v1.types import document_io -from google.cloud.documentai_v1.types import document_schema as gcd_document_schema -from google.cloud.documentai_v1.types import evaluation as gcd_evaluation -from google.cloud.documentai_v1.types import operation_metadata -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'ProcessOptions', - 'ProcessRequest', - 'HumanReviewStatus', - 'ProcessResponse', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'BatchProcessMetadata', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'GetProcessorTypeRequest', - 'GetProcessorRequest', - 'GetProcessorVersionRequest', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'DeleteProcessorVersionRequest', - 'DeleteProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'CreateProcessorRequest', - 'DeleteProcessorRequest', - 'DeleteProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EnableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'DisableProcessorMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'SetDefaultProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'ReviewDocumentOperationMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionResponse', - 'GetEvaluationRequest', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - }, -) - - -class ProcessOptions(proto.Message): - r"""Options for Process API - - 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: - individual_page_selector (google.cloud.documentai_v1.types.ProcessOptions.IndividualPageSelector): - Which pages to process (1-indexed). - - This field is a member of `oneof`_ ``page_range``. - from_start (int): - Only process certain pages from the start. - Process all if the document has fewer pages. - - This field is a member of `oneof`_ ``page_range``. - from_end (int): - Only process certain pages from the end, same - as above. - - This field is a member of `oneof`_ ``page_range``. - ocr_config (google.cloud.documentai_v1.types.OcrConfig): - Only applicable to ``OCR_PROCESSOR`` and - ``FORM_PARSER_PROCESSOR``. Returns error if set on other - processor types. - schema_override (google.cloud.documentai_v1.types.DocumentSchema): - Optional. Override the schema of the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - Will return an Invalid Argument error if this field is set - when the underlying - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - doesn't support schema override. - """ - - class IndividualPageSelector(proto.Message): - r"""A list of individual page numbers. - - Attributes: - pages (MutableSequence[int]): - Optional. Indices of the pages (starting from - 1). - """ - - pages: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=1, - ) - - individual_page_selector: IndividualPageSelector = proto.Field( - proto.MESSAGE, - number=5, - oneof='page_range', - message=IndividualPageSelector, - ) - from_start: int = proto.Field( - proto.INT32, - number=6, - oneof='page_range', - ) - from_end: int = proto.Field( - proto.INT32, - number=7, - oneof='page_range', - ) - ocr_config: document_io.OcrConfig = proto.Field( - proto.MESSAGE, - number=1, - message=document_io.OcrConfig, - ) - schema_override: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=8, - message=gcd_document_schema.DocumentSchema, - ) - - -class ProcessRequest(proto.Message): - r"""Request message for the - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - 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``. - gcs_document (google.cloud.documentai_v1.types.GcsDocument): - A raw document on Google Cloud Storage. - - 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 should be skipped for this request. - Default to ``false``. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies which fields to include in the - [ProcessResponse.document][google.cloud.documentai.v1.ProcessResponse.document] - output. Only supports top-level document and pages field, so - it must be in the form of ``{document_field_name}`` or - ``pages.{page_field_name}``. - process_options (google.cloud.documentai_v1.types.ProcessOptions): - Inference-time options for the process API - labels (MutableMapping[str, str]): - Optional. The labels with user-defined - metadata for the request. - Label keys and values can be no longer than 63 - characters (Unicode codepoints) and can only - contain lowercase letters, numeric characters, - underscores, and dashes. International - characters are allowed. Label values are - optional. Label keys must start with a letter. - """ - - inline_document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - raw_document: document_io.RawDocument = proto.Field( - proto.MESSAGE, - number=5, - oneof='source', - message=document_io.RawDocument, - ) - gcs_document: document_io.GcsDocument = proto.Field( - proto.MESSAGE, - number=8, - oneof='source', - message=document_io.GcsDocument, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=3, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=6, - message=field_mask_pb2.FieldMask, - ) - process_options: 'ProcessOptions' = proto.Field( - proto.MESSAGE, - number=7, - message='ProcessOptions', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - - -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][google.cloud.documentai.v1.HumanReviewStatus.state] - is ``HUMAN_REVIEW_IN_PROGRESS``. It has the same response - type and metadata as the long-running operation returned by - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument]. - """ - class State(proto.Enum): - r"""The final state of human review on a processed document. - - Values: - STATE_UNSPECIFIED (0): - Human review state is unspecified. Most - likely due to an internal error. - SKIPPED (1): - Human review is skipped for the document. - This can happen because human review isn't - enabled on the processor or the processing - request has been set to skip this document. - VALIDATION_PASSED (2): - Human review validation is triggered and - passed, so no review is needed. - IN_PROGRESS (3): - Human review validation is triggered and the - document is under review. - ERROR (4): - Some error happened during triggering human review, see the - [state_message][google.cloud.documentai.v1.HumanReviewStatus.state_message] - for details. - """ - STATE_UNSPECIFIED = 0 - SKIPPED = 1 - VALIDATION_PASSED = 2 - IN_PROGRESS = 3 - ERROR = 4 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ProcessResponse(proto.Message): - r"""Response message for the - [ProcessDocument][google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument] - method. - - Attributes: - document (google.cloud.documentai_v1.types.Document): - The document payload, will populate fields - based on the processor's behavior. - human_review_status (google.cloud.documentai_v1.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='HumanReviewStatus', - ) - - -class BatchProcessRequest(proto.Message): - r"""Request message for - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - 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 the - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments] - method. - document_output_config (google.cloud.documentai_v1.types.DocumentOutputConfig): - The output configuration for the - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments] - method. - skip_human_review (bool): - Whether human review should be skipped for this request. - Default to ``false``. - process_options (google.cloud.documentai_v1.types.ProcessOptions): - Inference-time options for the process API - labels (MutableMapping[str, str]): - Optional. The labels with user-defined - metadata for the request. - Label keys and values can be no longer than 63 - characters (Unicode codepoints) and can only - contain lowercase letters, numeric characters, - underscores, and dashes. International - characters are allowed. Label values are - optional. Label keys must start with a letter. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - input_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=5, - message=document_io.BatchDocumentsInputConfig, - ) - document_output_config: document_io.DocumentOutputConfig = proto.Field( - proto.MESSAGE, - number=6, - message=document_io.DocumentOutputConfig, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=4, - ) - process_options: 'ProcessOptions' = proto.Field( - proto.MESSAGE, - number=7, - message='ProcessOptions', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - - -class BatchProcessResponse(proto.Message): - r"""Response message for - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - """ - - -class BatchProcessMetadata(proto.Message): - r"""The long-running operation metadata for - [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]. - - Attributes: - state (google.cloud.documentai_v1.types.BatchProcessMetadata.State): - The state of the current batch processing. - state_message (str): - A message providing more details about the - current state of processing. For example, the - error message if the operation is failed. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - individual_process_statuses (MutableSequence[google.cloud.documentai_v1.types.BatchProcessMetadata.IndividualProcessStatus]): - The list of response details of each - document. - """ - class State(proto.Enum): - r"""Possible states of the batch processing operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - WAITING (1): - Request operation is waiting for scheduling. - RUNNING (2): - Request is being processed. - SUCCEEDED (3): - The batch processing completed successfully. - CANCELLING (4): - The batch processing was being cancelled. - CANCELLED (5): - The batch processing was cancelled. - FAILED (6): - The batch processing has failed. - """ - STATE_UNSPECIFIED = 0 - WAITING = 1 - RUNNING = 2 - SUCCEEDED = 3 - CANCELLING = 4 - CANCELLED = 5 - FAILED = 6 - - class IndividualProcessStatus(proto.Message): - r"""The status of a each individual document in the batch - process. - - Attributes: - input_gcs_source (str): - The source of the document, same as the - [input_gcs_source][google.cloud.documentai.v1.BatchProcessMetadata.IndividualProcessStatus.input_gcs_source] - field in the request when the batch process started. - status (google.rpc.status_pb2.Status): - The status processing the document. - output_gcs_destination (str): - The Cloud Storage output destination (in the request as - [DocumentOutputConfig.GcsOutputConfig.gcs_uri][google.cloud.documentai.v1.DocumentOutputConfig.GcsOutputConfig.gcs_uri]) - of the processed document if it was successful, otherwise - empty. - human_review_status (google.cloud.documentai_v1.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - input_gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - output_gcs_destination: str = proto.Field( - proto.STRING, - number=3, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=5, - message='HumanReviewStatus', - ) - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - individual_process_statuses: MutableSequence[IndividualProcessStatus] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=IndividualProcessStatus, - ) - - -class FetchProcessorTypesRequest(proto.Message): - r"""Request message for the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be added to an - allowlist. - - Attributes: - parent (str): - Required. The location of processor types to list. Format: - ``projects/{project}/locations/{location}``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FetchProcessorTypesResponse(proto.Message): - r"""Response message for the - [FetchProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes] - method. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1.types.ProcessorType]): - The list of processor types. - """ - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - - -class ListProcessorTypesRequest(proto.Message): - r"""Request message for the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be added to an - allowlist. - - Attributes: - parent (str): - Required. The location of processor types to list. Format: - ``projects/{project}/locations/{location}``. - page_size (int): - The maximum number of processor types to return. If - unspecified, at most ``100`` processor types will be - returned. The maximum value is ``500``. Values above ``500`` - will be coerced to ``500``. - page_token (str): - Used to retrieve the next page of results, - empty if at the end of the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListProcessorTypesResponse(proto.Message): - r"""Response message for the - [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] - method. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1.types.ProcessorType]): - The processor types. - next_page_token (str): - Points to the next page, otherwise empty. - """ - - @property - def raw_page(self): - return self - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListProcessorsRequest(proto.Message): - r"""Request message for list all processors belongs to a project. - - Attributes: - parent (str): - Required. The parent (project and location) which owns this - collection of Processors. Format: - ``projects/{project}/locations/{location}`` - page_size (int): - The maximum number of processors to return. If unspecified, - at most ``50`` processors will be returned. The maximum - value is ``100``. Values above ``100`` will be coerced to - ``100``. - page_token (str): - We will return the processors sorted by - creation time. The page token will point to the - next processor. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListProcessorsResponse(proto.Message): - r"""Response message for the - [ListProcessors][google.cloud.documentai.v1.DocumentProcessorService.ListProcessors] - method. - - Attributes: - processors (MutableSequence[google.cloud.documentai_v1.types.Processor]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processors: MutableSequence[gcd_processor.Processor] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.Processor, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetProcessorTypeRequest(proto.Message): - r"""Request message for the - [GetProcessorType][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType] - method. - - Attributes: - name (str): - Required. The processor type resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorRequest(proto.Message): - r"""Request message for the - [GetProcessor][google.cloud.documentai.v1.DocumentProcessorService.GetProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorVersionRequest(proto.Message): - r"""Request message for the - [GetProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProcessorVersionsRequest(proto.Message): - r"""Request message for list all processor versions belongs to a - processor. - - Attributes: - parent (str): - Required. The parent (project, location and processor) to - list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - page_size (int): - The maximum number of processor versions to return. If - unspecified, at most ``10`` processor versions will be - returned. The maximum value is ``20``. Values above ``20`` - will be coerced to ``20``. - page_token (str): - We will return the processor versions sorted - by creation time. The page token will point to - the next processor version. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListProcessorVersionsResponse(proto.Message): - r"""Response message for the - [ListProcessorVersions][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions] - method. - - Attributes: - processor_versions (MutableSequence[google.cloud.documentai_v1.types.ProcessorVersion]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processor_versions: MutableSequence[gcd_processor.ProcessorVersion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.ProcessorVersion, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteProcessorVersionRequest(proto.Message): - r"""Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor version resource name - to be deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [DeleteProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class DeployProcessorVersionRequest(proto.Message): - r"""Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor version resource name - to be deployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeployProcessorVersionResponse(proto.Message): - r"""Response message for the - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - method. - - """ - - -class DeployProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [DeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class UndeployProcessorVersionRequest(proto.Message): - r"""Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor version resource name - to be undeployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeployProcessorVersionResponse(proto.Message): - r"""Response message for the - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - method. - - """ - - -class UndeployProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [UndeployProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class CreateProcessorRequest(proto.Message): - r"""Request message for the - [CreateProcessor][google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized backend - service. If the - [ProcessorType][google.cloud.documentai.v1.ProcessorType] isn't - available in that region, the creation fails. - - 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][google.cloud.documentai.v1.Processor.type] - and - [Processor.display_name][google.cloud.documentai.v1.Processor.display_name] - to be set. Also, the - [Processor.kms_key_name][google.cloud.documentai.v1.Processor.kms_key_name] - field must be set if the processor is under CMEK. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - processor: gcd_processor.Processor = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_processor.Processor, - ) - - -class DeleteProcessorRequest(proto.Message): - r"""Request message for the - [DeleteProcessor][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name to be - deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorMetadata(proto.Message): - r"""The long-running operation metadata for the - [DeleteProcessor][google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class EnableProcessorRequest(proto.Message): - r"""Request message for the - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name to be - enabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EnableProcessorResponse(proto.Message): - r"""Response message for the - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - method. Intentionally empty proto for adding fields in future. - - """ - - -class EnableProcessorMetadata(proto.Message): - r"""The long-running operation metadata for the - [EnableProcessor][google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class DisableProcessorRequest(proto.Message): - r"""Request message for the - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name to be - disabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DisableProcessorResponse(proto.Message): - r"""Response message for the - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - method. Intentionally empty proto for adding fields in future. - - """ - - -class DisableProcessorMetadata(proto.Message): - r"""The long-running operation metadata for the - [DisableProcessor][google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class SetDefaultProcessorVersionRequest(proto.Message): - r"""Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - method. - - Attributes: - processor (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1.Processor] to change - default version. - default_processor_version (str): - Required. The resource name of child - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to use as default. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{version}`` - """ - - processor: str = proto.Field( - proto.STRING, - number=1, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SetDefaultProcessorVersionResponse(proto.Message): - r"""Response message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - method. - - """ - - -class SetDefaultProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class TrainProcessorVersionRequest(proto.Message): - r"""Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion] - method. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - custom_document_extraction_options (google.cloud.documentai_v1.types.TrainProcessorVersionRequest.CustomDocumentExtractionOptions): - Options to control Custom Document Extraction - (CDE) Processor. - - This field is a member of `oneof`_ ``processor_flags``. - parent (str): - Required. The parent (project, location and processor) to - create the new version for. Format: - ``projects/{project}/locations/{location}/processors/{processor}``. - processor_version (google.cloud.documentai_v1.types.ProcessorVersion): - Required. The processor version to be - created. - document_schema (google.cloud.documentai_v1.types.DocumentSchema): - Optional. The schema the processor version - will be trained with. - input_data (google.cloud.documentai_v1.types.TrainProcessorVersionRequest.InputData): - Optional. The input data used to train the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - base_processor_version (str): - Optional. The processor version to use as a base for - training. This processor version must be a child of - ``parent``. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}``. - """ - - class InputData(proto.Message): - r"""The input data used to train a new - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - - Attributes: - training_documents (google.cloud.documentai_v1.types.BatchDocumentsInputConfig): - The documents used for training the new - version. - test_documents (google.cloud.documentai_v1.types.BatchDocumentsInputConfig): - The documents used for testing the trained - version. - """ - - training_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=3, - message=document_io.BatchDocumentsInputConfig, - ) - test_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=4, - message=document_io.BatchDocumentsInputConfig, - ) - - class CustomDocumentExtractionOptions(proto.Message): - r"""Options to control the training of the Custom Document - Extraction (CDE) Processor. - - Attributes: - training_method (google.cloud.documentai_v1.types.TrainProcessorVersionRequest.CustomDocumentExtractionOptions.TrainingMethod): - Training method to use for CDE training. - """ - class TrainingMethod(proto.Enum): - r"""Training Method for CDE. ``TRAINING_METHOD_UNSPECIFIED`` will fall - back to ``MODEL_BASED``. - - Values: - TRAINING_METHOD_UNSPECIFIED (0): - No description available. - MODEL_BASED (1): - No description available. - TEMPLATE_BASED (2): - No description available. - """ - TRAINING_METHOD_UNSPECIFIED = 0 - MODEL_BASED = 1 - TEMPLATE_BASED = 2 - - training_method: 'TrainProcessorVersionRequest.CustomDocumentExtractionOptions.TrainingMethod' = proto.Field( - proto.ENUM, - number=3, - enum='TrainProcessorVersionRequest.CustomDocumentExtractionOptions.TrainingMethod', - ) - - custom_document_extraction_options: CustomDocumentExtractionOptions = proto.Field( - proto.MESSAGE, - number=5, - oneof='processor_flags', - message=CustomDocumentExtractionOptions, - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - processor_version: gcd_processor.ProcessorVersion = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_processor.ProcessorVersion, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=10, - message=gcd_document_schema.DocumentSchema, - ) - input_data: InputData = proto.Field( - proto.MESSAGE, - number=4, - message=InputData, - ) - base_processor_version: str = proto.Field( - proto.STRING, - number=8, - ) - - -class TrainProcessorVersionResponse(proto.Message): - r"""The response for - [TrainProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion]. - - Attributes: - processor_version (str): - The resource name of the processor version - produced by training. - """ - - processor_version: str = proto.Field( - proto.STRING, - number=1, - ) - - -class TrainProcessorVersionMetadata(proto.Message): - r"""The metadata that represents a processor version being - created. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - training_dataset_validation (google.cloud.documentai_v1.types.TrainProcessorVersionMetadata.DatasetValidation): - The training dataset validation information. - test_dataset_validation (google.cloud.documentai_v1.types.TrainProcessorVersionMetadata.DatasetValidation): - The test dataset validation information. - """ - - class DatasetValidation(proto.Message): - r"""The dataset validation information. - This includes any and all errors with documents and the dataset. - - Attributes: - document_error_count (int): - The total number of document errors. - dataset_error_count (int): - The total number of dataset errors. - document_errors (MutableSequence[google.rpc.status_pb2.Status]): - Error information pertaining to specific - documents. A maximum of 10 document errors will - be returned. Any document with errors will not - be used throughout training. - dataset_errors (MutableSequence[google.rpc.status_pb2.Status]): - Error information for the dataset as a whole. - A maximum of 10 dataset errors will be returned. - A single dataset error is terminal for training. - """ - - document_error_count: int = proto.Field( - proto.INT32, - number=3, - ) - dataset_error_count: int = proto.Field( - proto.INT32, - number=4, - ) - document_errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - dataset_errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - training_dataset_validation: DatasetValidation = proto.Field( - proto.MESSAGE, - number=2, - message=DatasetValidation, - ) - test_dataset_validation: DatasetValidation = proto.Field( - proto.MESSAGE, - number=3, - message=DatasetValidation, - ) - - -class ReviewDocumentRequest(proto.Message): - r"""Request message for the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - 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][google.cloud.documentai.v1.HumanReviewConfig] - that the document will be reviewed with. - enable_schema_validation (bool): - Whether the validation should be performed on - the ad-hoc review request. - priority (google.cloud.documentai_v1.types.ReviewDocumentRequest.Priority): - The priority of the human review task. - document_schema (google.cloud.documentai_v1.types.DocumentSchema): - The document schema of the human review task. - """ - class Priority(proto.Enum): - r"""The priority level of the human review task. - - Values: - DEFAULT (0): - The default priority level. - URGENT (1): - The urgent priority level. The labeling - manager should allocate labeler resource to the - urgent task queue to respect this priority - level. - """ - DEFAULT = 0 - URGENT = 1 - - inline_document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - human_review_config: str = proto.Field( - proto.STRING, - number=1, - ) - enable_schema_validation: bool = proto.Field( - proto.BOOL, - number=3, - ) - priority: Priority = proto.Field( - proto.ENUM, - number=5, - enum=Priority, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_document_schema.DocumentSchema, - ) - - -class ReviewDocumentResponse(proto.Message): - r"""Response message for the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - method. - - Attributes: - gcs_destination (str): - The Cloud Storage uri for the human reviewed - document if the review is succeeded. - state (google.cloud.documentai_v1.types.ReviewDocumentResponse.State): - The state of the review operation. - rejection_reason (str): - The reason why the review is rejected by - reviewer. - """ - class State(proto.Enum): - r"""Possible states of the review operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - REJECTED (1): - The review operation is rejected by the - reviewer. - SUCCEEDED (2): - The review operation is succeeded. - """ - STATE_UNSPECIFIED = 0 - REJECTED = 1 - SUCCEEDED = 2 - - gcs_destination: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - rejection_reason: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ReviewDocumentOperationMetadata(proto.Message): - r"""The long-running operation metadata for the - [ReviewDocument][google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - question_id (str): - The Crowd Compute question ID. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - question_id: str = proto.Field( - proto.STRING, - number=6, - ) - - -class EvaluateProcessorVersionRequest(proto.Message): - r"""Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - against the supplied documents. - - Attributes: - processor_version (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to evaluate. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - evaluation_documents (google.cloud.documentai_v1.types.BatchDocumentsInputConfig): - Optional. The documents used in the - evaluation. If unspecified, use the processor's - dataset as evaluation input. - """ - - processor_version: str = proto.Field( - proto.STRING, - number=1, - ) - evaluation_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=3, - message=document_io.BatchDocumentsInputConfig, - ) - - -class EvaluateProcessorVersionMetadata(proto.Message): - r"""Metadata of the - [EvaluateProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class EvaluateProcessorVersionResponse(proto.Message): - r"""Response of the - [EvaluateProcessorVersion][google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion] - method. - - Attributes: - evaluation (str): - The resource name of the created evaluation. - """ - - evaluation: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEvaluationRequest(proto.Message): - r"""Retrieves a specific Evaluation. - - Attributes: - name (str): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1.Evaluation] to get. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEvaluationsRequest(proto.Message): - r"""Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion]. - - Attributes: - parent (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion] - to list evaluations for. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - page_size (int): - The standard list page size. If unspecified, at most ``5`` - evaluations are returned. The maximum value is ``100``. - Values above ``100`` are coerced to ``100``. - page_token (str): - A page token, received from a previous ``ListEvaluations`` - call. Provide this to retrieve the subsequent page. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEvaluationsResponse(proto.Message): - r"""The response from ``ListEvaluations``. - - Attributes: - evaluations (MutableSequence[google.cloud.documentai_v1.types.Evaluation]): - The evaluations requested. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - evaluations: MutableSequence[gcd_evaluation.Evaluation] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_evaluation.Evaluation, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_schema.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_schema.py deleted file mode 100644 index 7cb31bfce6ad..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/document_schema.py +++ /dev/null @@ -1,258 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'DocumentSchema', - }, -) - - -class DocumentSchema(proto.Message): - r"""The schema defines the output of the processed document by a - processor. - - Attributes: - display_name (str): - Display name to show to users. - description (str): - Description of the schema. - entity_types (MutableSequence[google.cloud.documentai_v1.types.DocumentSchema.EntityType]): - Entity types of the schema. - metadata (google.cloud.documentai_v1.types.DocumentSchema.Metadata): - Metadata of the schema. - """ - - class EntityType(proto.Message): - r"""EntityType is the wrapper of a label of the corresponding - model with detailed attributes and limitations for entity-based - processors. Multiple types can also compose a dependency tree to - represent nested types. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - enum_values (google.cloud.documentai_v1.types.DocumentSchema.EntityType.EnumValues): - If specified, lists all the possible values for this entity. - This should not be more than a handful of values. If the - number of values is >10 or could change frequently use the - ``EntityType.value_ontology`` field and specify a list of - all possible values in a value ontology file. - - This field is a member of `oneof`_ ``value_source``. - display_name (str): - User defined name for the type. - name (str): - Name of the type. It must be unique within the schema file - and cannot be a "Common Type". The following naming - conventions are used: - - - Use ``snake_casing``. - - Name matching is case-sensitive. - - Maximum 64 characters. - - Must start with a letter. - - Allowed characters: ASCII letters ``[a-z0-9_-]``. (For - backward compatibility internal infrastructure and - tooling can handle any ascii character.) - - The ``/`` is sometimes used to denote a property of a - type. For example ``line_item/amount``. This convention - is deprecated, but will still be honored for backward - compatibility. - base_types (MutableSequence[str]): - The entity type that this type is derived - from. For now, one and only one should be set. - properties (MutableSequence[google.cloud.documentai_v1.types.DocumentSchema.EntityType.Property]): - Description the nested structure, or - composition of an entity. - """ - - class EnumValues(proto.Message): - r"""Defines the a list of enum values. - - Attributes: - values (MutableSequence[str]): - The individual values that this enum values - type can include. - """ - - values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class Property(proto.Message): - r"""Defines properties that can be part of the entity type. - - Attributes: - name (str): - The name of the property. Follows the same - guidelines as the EntityType name. - display_name (str): - User defined name for the property. - value_type (str): - A reference to the value type of the property. This type is - subject to the same conventions as the ``Entity.base_types`` - field. - occurrence_type (google.cloud.documentai_v1.types.DocumentSchema.EntityType.Property.OccurrenceType): - Occurrence type limits the number of - instances an entity type appears in the - document. - """ - class OccurrenceType(proto.Enum): - r"""Types of occurrences of the entity type in the document. This - represents the number of instances, not mentions, of an entity. For - example, a bank statement might only have one ``account_number``, - but this account number can be mentioned in several places on the - document. In this case, the ``account_number`` is considered a - ``REQUIRED_ONCE`` entity type. If, on the other hand, we expect a - bank statement to contain the status of multiple different accounts - for the customers, the occurrence type is set to - ``REQUIRED_MULTIPLE``. - - Values: - OCCURRENCE_TYPE_UNSPECIFIED (0): - Unspecified occurrence type. - OPTIONAL_ONCE (1): - There will be zero or one instance of this - entity type. The same entity instance may be - mentioned multiple times. - OPTIONAL_MULTIPLE (2): - The entity type will appear zero or multiple - times. - REQUIRED_ONCE (3): - The entity type will only appear exactly - once. The same entity instance may be mentioned - multiple times. - REQUIRED_MULTIPLE (4): - The entity type will appear once or more - times. - """ - OCCURRENCE_TYPE_UNSPECIFIED = 0 - OPTIONAL_ONCE = 1 - OPTIONAL_MULTIPLE = 2 - REQUIRED_ONCE = 3 - REQUIRED_MULTIPLE = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=6, - ) - value_type: str = proto.Field( - proto.STRING, - number=2, - ) - occurrence_type: 'DocumentSchema.EntityType.Property.OccurrenceType' = proto.Field( - proto.ENUM, - number=3, - enum='DocumentSchema.EntityType.Property.OccurrenceType', - ) - - enum_values: 'DocumentSchema.EntityType.EnumValues' = proto.Field( - proto.MESSAGE, - number=14, - oneof='value_source', - message='DocumentSchema.EntityType.EnumValues', - ) - display_name: str = proto.Field( - proto.STRING, - number=13, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - base_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - properties: MutableSequence['DocumentSchema.EntityType.Property'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='DocumentSchema.EntityType.Property', - ) - - class Metadata(proto.Message): - r"""Metadata for global schema behavior. - - Attributes: - document_splitter (bool): - If true, a ``document`` entity type can be applied to - subdocument (splitting). Otherwise, it can only be applied - to the entire document (classification). - document_allow_multiple_labels (bool): - If true, on a given page, there can be multiple ``document`` - annotations covering it. - prefixed_naming_on_properties (bool): - If set, all the nested entities must be - prefixed with the parents. - skip_naming_validation (bool): - If set, we will skip the naming format validation in the - schema. So the string values in - ``DocumentSchema.EntityType.name`` and - ``DocumentSchema.EntityType.Property.name`` will not be - checked. - """ - - document_splitter: bool = proto.Field( - proto.BOOL, - number=1, - ) - document_allow_multiple_labels: bool = proto.Field( - proto.BOOL, - number=2, - ) - prefixed_naming_on_properties: bool = proto.Field( - proto.BOOL, - number=6, - ) - skip_naming_validation: bool = proto.Field( - proto.BOOL, - number=7, - ) - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - entity_types: MutableSequence[EntityType] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=EntityType, - ) - metadata: Metadata = proto.Field( - proto.MESSAGE, - number=4, - message=Metadata, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/evaluation.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/evaluation.py deleted file mode 100644 index 3d65fe5a3a0d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/evaluation.py +++ /dev/null @@ -1,344 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'EvaluationReference', - 'Evaluation', - }, -) - - -class EvaluationReference(proto.Message): - r"""Gives a short summary of an evaluation, and links to the - evaluation itself. - - Attributes: - operation (str): - The resource name of the Long Running - Operation for the evaluation. - evaluation (str): - The resource name of the evaluation. - aggregate_metrics (google.cloud.documentai_v1.types.Evaluation.Metrics): - An aggregate of the statistics for the - evaluation with fuzzy matching on. - aggregate_metrics_exact (google.cloud.documentai_v1.types.Evaluation.Metrics): - An aggregate of the statistics for the - evaluation with fuzzy matching off. - """ - - operation: str = proto.Field( - proto.STRING, - number=1, - ) - evaluation: str = proto.Field( - proto.STRING, - number=2, - ) - aggregate_metrics: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=4, - message='Evaluation.Metrics', - ) - aggregate_metrics_exact: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=5, - message='Evaluation.Metrics', - ) - - -class Evaluation(proto.Message): - r"""An evaluation of a ProcessorVersion's performance. - - Attributes: - name (str): - The resource name of the evaluation. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the evaluation was created. - document_counters (google.cloud.documentai_v1.types.Evaluation.Counters): - Counters for the documents used in the - evaluation. - all_entities_metrics (google.cloud.documentai_v1.types.Evaluation.MultiConfidenceMetrics): - Metrics for all the entities in aggregate. - entity_metrics (MutableMapping[str, google.cloud.documentai_v1.types.Evaluation.MultiConfidenceMetrics]): - Metrics across confidence levels, for - different entities. - kms_key_name (str): - The KMS key name used for encryption. - kms_key_version_name (str): - The KMS key version with which data is - encrypted. - """ - - class Counters(proto.Message): - r"""Evaluation counters for the documents that were used. - - Attributes: - input_documents_count (int): - How many documents were sent for evaluation. - invalid_documents_count (int): - How many documents were not included in the - evaluation as they didn't pass validation. - failed_documents_count (int): - How many documents were not included in the - evaluation as Document AI failed to process - them. - evaluated_documents_count (int): - How many documents were used in the - evaluation. - """ - - input_documents_count: int = proto.Field( - proto.INT32, - number=1, - ) - invalid_documents_count: int = proto.Field( - proto.INT32, - number=2, - ) - failed_documents_count: int = proto.Field( - proto.INT32, - number=3, - ) - evaluated_documents_count: int = proto.Field( - proto.INT32, - number=4, - ) - - class Metrics(proto.Message): - r"""Evaluation metrics, either in aggregate or about a specific - entity. - - Attributes: - precision (float): - The calculated precision. - recall (float): - The calculated recall. - f1_score (float): - The calculated f1 score. - predicted_occurrences_count (int): - The amount of occurrences in predicted - documents. - ground_truth_occurrences_count (int): - The amount of occurrences in ground truth - documents. - predicted_document_count (int): - The amount of documents with a predicted - occurrence. - ground_truth_document_count (int): - The amount of documents with a ground truth - occurrence. - true_positives_count (int): - The amount of true positives. - false_positives_count (int): - The amount of false positives. - false_negatives_count (int): - The amount of false negatives. - total_documents_count (int): - The amount of documents that had an - occurrence of this label. - """ - - precision: float = proto.Field( - proto.FLOAT, - number=1, - ) - recall: float = proto.Field( - proto.FLOAT, - number=2, - ) - f1_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - predicted_occurrences_count: int = proto.Field( - proto.INT32, - number=4, - ) - ground_truth_occurrences_count: int = proto.Field( - proto.INT32, - number=5, - ) - predicted_document_count: int = proto.Field( - proto.INT32, - number=10, - ) - ground_truth_document_count: int = proto.Field( - proto.INT32, - number=11, - ) - true_positives_count: int = proto.Field( - proto.INT32, - number=6, - ) - false_positives_count: int = proto.Field( - proto.INT32, - number=7, - ) - false_negatives_count: int = proto.Field( - proto.INT32, - number=8, - ) - total_documents_count: int = proto.Field( - proto.INT32, - number=9, - ) - - class ConfidenceLevelMetrics(proto.Message): - r"""Evaluations metrics, at a specific confidence level. - - Attributes: - confidence_level (float): - The confidence level. - metrics (google.cloud.documentai_v1.types.Evaluation.Metrics): - The metrics at the specific confidence level. - """ - - confidence_level: float = proto.Field( - proto.FLOAT, - number=1, - ) - metrics: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=2, - message='Evaluation.Metrics', - ) - - class MultiConfidenceMetrics(proto.Message): - r"""Metrics across multiple confidence levels. - - Attributes: - confidence_level_metrics (MutableSequence[google.cloud.documentai_v1.types.Evaluation.ConfidenceLevelMetrics]): - Metrics across confidence levels with fuzzy - matching enabled. - confidence_level_metrics_exact (MutableSequence[google.cloud.documentai_v1.types.Evaluation.ConfidenceLevelMetrics]): - Metrics across confidence levels with only - exact matching. - auprc (float): - The calculated area under the precision - recall curve (AUPRC), computed by integrating - over all confidence thresholds. - estimated_calibration_error (float): - The Estimated Calibration Error (ECE) of the - confidence of the predicted entities. - auprc_exact (float): - The AUPRC for metrics with fuzzy matching - disabled, i.e., exact matching only. - estimated_calibration_error_exact (float): - The ECE for the predicted entities with fuzzy - matching disabled, i.e., exact matching only. - metrics_type (google.cloud.documentai_v1.types.Evaluation.MultiConfidenceMetrics.MetricsType): - The metrics type for the label. - """ - class MetricsType(proto.Enum): - r"""A type that determines how metrics should be interpreted. - - Values: - METRICS_TYPE_UNSPECIFIED (0): - The metrics type is unspecified. By default, - metrics without a particular specification are - for leaf entity types (i.e., top-level entity - types without child types, or child types which - are not parent types themselves). - AGGREGATE (1): - Indicates whether metrics for this particular - label type represent an aggregate of metrics for - other types instead of being based on actual - TP/FP/FN values for the label type. Metrics for - parent (i.e., non-leaf) entity types are an - aggregate of metrics for their children. - """ - METRICS_TYPE_UNSPECIFIED = 0 - AGGREGATE = 1 - - confidence_level_metrics: MutableSequence['Evaluation.ConfidenceLevelMetrics'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Evaluation.ConfidenceLevelMetrics', - ) - confidence_level_metrics_exact: MutableSequence['Evaluation.ConfidenceLevelMetrics'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Evaluation.ConfidenceLevelMetrics', - ) - auprc: float = proto.Field( - proto.FLOAT, - number=2, - ) - estimated_calibration_error: float = proto.Field( - proto.FLOAT, - number=3, - ) - auprc_exact: float = proto.Field( - proto.FLOAT, - number=5, - ) - estimated_calibration_error_exact: float = proto.Field( - proto.FLOAT, - number=6, - ) - metrics_type: 'Evaluation.MultiConfidenceMetrics.MetricsType' = proto.Field( - proto.ENUM, - number=7, - enum='Evaluation.MultiConfidenceMetrics.MetricsType', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - document_counters: Counters = proto.Field( - proto.MESSAGE, - number=5, - message=Counters, - ) - all_entities_metrics: MultiConfidenceMetrics = proto.Field( - proto.MESSAGE, - number=3, - message=MultiConfidenceMetrics, - ) - entity_metrics: MutableMapping[str, MultiConfidenceMetrics] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=MultiConfidenceMetrics, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=6, - ) - kms_key_version_name: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/geometry.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/geometry.py deleted file mode 100644 index a9478d1a35bc..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/geometry.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'Vertex', - 'NormalizedVertex', - 'BoundingPoly', - }, -) - - -class Vertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the vertex coordinates are in the same scale as the - original image. - - Attributes: - x (int): - X coordinate. - y (int): - Y coordinate (starts from the top of the - image). - """ - - x: int = proto.Field( - proto.INT32, - number=1, - ) - y: int = proto.Field( - proto.INT32, - number=2, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate (starts from the top of the - image). - """ - - x: float = proto.Field( - proto.FLOAT, - number=1, - ) - y: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class BoundingPoly(proto.Message): - r"""A bounding polygon for the detected image annotation. - - Attributes: - vertices (MutableSequence[google.cloud.documentai_v1.types.Vertex]): - The bounding polygon vertices. - normalized_vertices (MutableSequence[google.cloud.documentai_v1.types.NormalizedVertex]): - The bounding polygon normalized vertices. - """ - - vertices: MutableSequence['Vertex'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/operation_metadata.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/operation_metadata.py deleted file mode 100644 index 935d4a9ff25e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/operation_metadata.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'CommonOperationMetadata', - }, -) - - -class CommonOperationMetadata(proto.Message): - r"""The common metadata for long running operations. - - Attributes: - state (google.cloud.documentai_v1.types.CommonOperationMetadata.State): - The state of the operation. - state_message (str): - A message providing more details about the - current state of processing. - resource (str): - A related resource to this operation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - """ - class State(proto.Enum): - r"""State of the longrunning operation. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - RUNNING (1): - Operation is still running. - CANCELLING (2): - Operation is being cancelled. - SUCCEEDED (3): - Operation succeeded. - FAILED (4): - Operation failed. - CANCELLED (5): - Operation is cancelled. - """ - STATE_UNSPECIFIED = 0 - RUNNING = 1 - CANCELLING = 2 - SUCCEEDED = 3 - FAILED = 4 - CANCELLED = 5 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - resource: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/processor.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/processor.py deleted file mode 100644 index 1223fff01138..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/processor.py +++ /dev/null @@ -1,344 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1.types import document_schema as gcd_document_schema -from google.cloud.documentai_v1.types import evaluation -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'ProcessorVersion', - 'ProcessorVersionAlias', - 'Processor', - }, -) - - -class ProcessorVersion(proto.Message): - r"""A processor version is an implementation of a processor. Each - processor can have multiple versions, pretrained by Google - internally or uptrained by the customer. A processor can only - have one default version at a time. Its document-processing - behavior is defined by that version. - - Attributes: - name (str): - The resource name of the processor version. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}`` - display_name (str): - The display name of the processor version. - document_schema (google.cloud.documentai_v1.types.DocumentSchema): - The schema of the processor version. - Describes the output. - state (google.cloud.documentai_v1.types.ProcessorVersion.State): - The state of the processor version. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the processor version was created. - latest_evaluation (google.cloud.documentai_v1.types.EvaluationReference): - The most recently invoked evaluation for the - processor version. - kms_key_name (str): - The KMS key name used for encryption. - kms_key_version_name (str): - The KMS key version with which data is - encrypted. - google_managed (bool): - Output only. 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. - model_type (google.cloud.documentai_v1.types.ProcessorVersion.ModelType): - Output only. The model type of this processor - version. - """ - class State(proto.Enum): - r"""The possible states of the processor version. - - Values: - STATE_UNSPECIFIED (0): - The processor version is in an unspecified - state. - DEPLOYED (1): - The processor version is deployed and can be - used for processing. - DEPLOYING (2): - The processor version is being deployed. - UNDEPLOYED (3): - The processor version is not deployed and - cannot be used for processing. - UNDEPLOYING (4): - The processor version is being undeployed. - CREATING (5): - The processor version is being created. - DELETING (6): - The processor version is being deleted. - FAILED (7): - The processor version failed and is in an - indeterminate state. - IMPORTING (8): - The processor version is being imported. - """ - STATE_UNSPECIFIED = 0 - DEPLOYED = 1 - DEPLOYING = 2 - UNDEPLOYED = 3 - UNDEPLOYING = 4 - CREATING = 5 - DELETING = 6 - FAILED = 7 - IMPORTING = 8 - - class ModelType(proto.Enum): - r"""The possible model types of the processor version. - - Values: - MODEL_TYPE_UNSPECIFIED (0): - The processor version has unspecified model - type. - MODEL_TYPE_GENERATIVE (1): - The processor version has generative model - type. - MODEL_TYPE_CUSTOM (2): - The processor version has custom model type. - """ - MODEL_TYPE_UNSPECIFIED = 0 - MODEL_TYPE_GENERATIVE = 1 - MODEL_TYPE_CUSTOM = 2 - - class DeprecationInfo(proto.Message): - r"""Information about the upcoming deprecation of this processor - version. - - Attributes: - deprecation_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which this processor version will - be deprecated. - replacement_processor_version (str): - If set, the processor version that will be - used as a replacement. - """ - - deprecation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - replacement_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=12, - message=gcd_document_schema.DocumentSchema, - ) - state: State = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - latest_evaluation: evaluation.EvaluationReference = proto.Field( - proto.MESSAGE, - number=8, - message=evaluation.EvaluationReference, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=9, - ) - kms_key_version_name: str = proto.Field( - proto.STRING, - number=10, - ) - google_managed: bool = proto.Field( - proto.BOOL, - number=11, - ) - deprecation_info: DeprecationInfo = proto.Field( - proto.MESSAGE, - number=13, - message=DeprecationInfo, - ) - model_type: ModelType = proto.Field( - proto.ENUM, - number=15, - enum=ModelType, - ) - - -class ProcessorVersionAlias(proto.Message): - r"""Contains the alias and the aliased resource name of processor - version. - - Attributes: - alias (str): - The alias in the form of ``processor_version`` resource - name. - processor_version (str): - The resource name of aliased processor - version. - """ - - alias: str = proto.Field( - proto.STRING, - number=1, - ) - processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -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, such as: ``OCR_PROCESSOR``, - ``INVOICE_PROCESSOR``. To get a list of processor 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. - processor_version_aliases (MutableSequence[google.cloud.documentai_v1.types.ProcessorVersionAlias]): - Output only. The processor version aliases. - 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 and decryption in CMEK scenarios. - """ - class State(proto.Enum): - r"""The possible states of the processor. - - Values: - STATE_UNSPECIFIED (0): - The processor is in an unspecified state. - ENABLED (1): - The processor is enabled, i.e., has an - enabled version which can currently serve - processing requests and all the feature - dependencies have been successfully initialized. - DISABLED (2): - The processor is disabled. - ENABLING (3): - The processor is being enabled, will become ``ENABLED`` if - successful. - DISABLING (4): - The processor is being disabled, will become ``DISABLED`` if - successful. - CREATING (5): - The processor is being created, will become either - ``ENABLED`` (for successful creation) or ``FAILED`` (for - failed ones). Once a processor is in this state, it can then - be used for document processing, but the feature - dependencies of the processor might not be fully created - yet. - FAILED (6): - The processor failed during creation or - initialization of feature dependencies. The user - should delete the processor and recreate one as - all the functionalities of the processor are - disabled. - DELETING (7): - The processor is being deleted, will be - removed if successful. - """ - STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - ENABLING = 3 - DISABLING = 4 - CREATING = 5 - FAILED = 6 - DELETING = 7 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=9, - ) - processor_version_aliases: MutableSequence['ProcessorVersionAlias'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='ProcessorVersionAlias', - ) - process_endpoint: str = proto.Field( - proto.STRING, - number=6, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/processor_type.py b/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/processor_type.py deleted file mode 100644 index da00490329bb..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/google/cloud/documentai_v1/types/processor_type.py +++ /dev/null @@ -1,109 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.api import launch_stage_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1', - manifest={ - 'ProcessorType', - }, -) - - -class ProcessorType(proto.Message): - r"""A processor type is responsible for performing a certain - document understanding task on a certain type of document. - - Attributes: - name (str): - The resource name of the processor type. Format: - ``projects/{project}/processorTypes/{processor_type}`` - type_ (str): - The processor type, such as: ``OCR_PROCESSOR``, - ``INVOICE_PROCESSOR``. - category (str): - The processor category, used by UI to group - processor types. - available_locations (MutableSequence[google.cloud.documentai_v1.types.ProcessorType.LocationInfo]): - The locations in which this processor is - available. - allow_creation (bool): - Whether the processor type allows creation. - If true, users can create a processor of this - processor type. Otherwise, users need to request - access. - launch_stage (google.api.launch_stage_pb2.LaunchStage): - Launch stage of the processor type - sample_document_uris (MutableSequence[str]): - A set of Cloud Storage URIs of sample - documents for this processor. - """ - - class LocationInfo(proto.Message): - r"""The location information about where the processor is - available. - - Attributes: - location_id (str): - The location ID. For supported locations, refer to `regional - and multi-regional support `__. - """ - - location_id: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - category: str = proto.Field( - proto.STRING, - number=3, - ) - available_locations: MutableSequence[LocationInfo] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=LocationInfo, - ) - allow_creation: bool = proto.Field( - proto.BOOL, - number=6, - ) - launch_stage: launch_stage_pb2.LaunchStage = proto.Field( - proto.ENUM, - number=8, - enum=launch_stage_pb2.LaunchStage, - ) - sample_document_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1/mypy.ini b/owl-bot-staging/google-cloud-documentai/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-documentai/v1/noxfile.py b/owl-bot-staging/google-cloud-documentai/v1/noxfile.py deleted file mode 100644 index aa678017e991..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/noxfile.py +++ /dev/null @@ -1,253 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-documentai' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@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=ALL_PYTHON[-1]) -def prerelease_deps(session): - """Run the unit test suite against pre-release versions of dependencies.""" - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/documentai_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - '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==7.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, - ) diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py deleted file mode 100644 index 838191ca2a19..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py deleted file mode 100644 index 7e31716e1981..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_batch_process_documents_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py deleted file mode 100644 index aec35df3641a..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py deleted file mode 100644 index 8be9b136d393..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_create_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py deleted file mode 100644 index b0ec37cd2623..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py deleted file mode 100644 index 6246e2b10b90..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py deleted file mode 100644 index cf7011fd0c66..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py deleted file mode 100644 index b1bf9bc62cfc..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_delete_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py deleted file mode 100644 index fd799c9a00a2..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py deleted file mode 100644 index caa1d64c1116..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py deleted file mode 100644 index 88d5c359e296..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py deleted file mode 100644 index 4df7cf6ce765..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_disable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py deleted file mode 100644 index dbde55cf1ea5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py deleted file mode 100644 index a649f984ef47..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_enable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py deleted file mode 100644 index 4ee87bfff151..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EvaluateProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -async def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py deleted file mode 100644 index aacabdc2234e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EvaluateProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py deleted file mode 100644 index 921449a0f514..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py deleted file mode 100644 index bb003303736b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py deleted file mode 100644 index d7741ddc902d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_GetEvaluation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -async def sample_get_evaluation(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_evaluation(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetEvaluation_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py deleted file mode 100644 index c8e46af881b7..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_evaluation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_GetEvaluation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -def sample_get_evaluation(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = client.get_evaluation(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetEvaluation_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py deleted file mode 100644 index 0e94d1f0b6f6..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py deleted file mode 100644 index 2a84758df135..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py deleted file mode 100644 index 24e2340ce417..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProcessorType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_GetProcessorType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -async def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessorType_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py deleted file mode 100644 index 05c47d3e2c7d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProcessorType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_GetProcessorType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -def sample_get_processor_type(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_GetProcessorType_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py deleted file mode 100644 index a6b8113fe52e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py deleted file mode 100644 index b4adff93f1c2..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_get_processor_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py deleted file mode 100644 index fc6f9a098001..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEvaluations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_ListEvaluations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -async def sample_list_evaluations(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListEvaluations_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py deleted file mode 100644 index 55d6530f7e5d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_evaluations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEvaluations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_ListEvaluations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -def sample_list_evaluations(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_ListEvaluations_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py deleted file mode 100644 index 59db2176472e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py deleted file mode 100644 index 497c834d4301..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py deleted file mode 100644 index c46b9eda02e8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py deleted file mode 100644 index 3677d64d7eef..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processor_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py deleted file mode 100644 index ac4857318d63..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py deleted file mode 100644 index 3f1594a63212..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_list_processors_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py deleted file mode 100644 index b721e4bea44f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py deleted file mode 100644 index eb18086da3f4..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_process_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py deleted file mode 100644 index 3ff5c1b69e3e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py deleted file mode 100644 index d29620e11100..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_review_document_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py deleted file mode 100644 index 036fa7d23cdf..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py deleted file mode 100644 index 3a8c4e1d7ff6..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py deleted file mode 100644 index e7f2061e6060..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_TrainProcessorVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -async def sample_train_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_TrainProcessorVersion_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py deleted file mode 100644 index 922f52a50280..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_train_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1_generated_DocumentProcessorService_TrainProcessorVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1 - - -def sample_train_processor_version(): - # Create a client - client = documentai_v1.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1_generated_DocumentProcessorService_TrainProcessorVersion_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py deleted file mode 100644 index 16585aeacc4b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py deleted file mode 100644 index 45efaee12c15..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json b/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json deleted file mode 100644 index 96d60af285a2..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json +++ /dev/null @@ -1,3549 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.documentai.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-documentai", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.BatchProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1_generated_document_processor_service_batch_process_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_batch_process_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.BatchProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1_generated_document_processor_service_batch_process_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_BatchProcessDocuments_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_batch_process_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1.types.Processor" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1_generated_document_processor_service_create_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_CreateProcessor_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_create_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1.types.Processor" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1_generated_document_processor_service_create_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_CreateProcessor_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_create_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_delete_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_delete_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_delete_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_delete_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1_generated_document_processor_service_delete_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessor_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_delete_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeleteProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1_generated_document_processor_service_delete_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeleteProcessor_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_delete_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_deploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_deploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DeployProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_deploy_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DisableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1_generated_document_processor_service_disable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DisableProcessor_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_disable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.DisableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1_generated_document_processor_service_disable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_DisableProcessor_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_disable_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.EnableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1_generated_document_processor_service_enable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_EnableProcessor_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_enable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.EnableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1_generated_document_processor_service_enable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_EnableProcessor_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_enable_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.evaluate_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EvaluateProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.EvaluateProcessorVersionRequest" - }, - { - "name": "processor_version", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "evaluate_processor_version" - }, - "description": "Sample for EvaluateProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_evaluate_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.evaluate_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.EvaluateProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EvaluateProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.EvaluateProcessorVersionRequest" - }, - { - "name": "processor_version", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "evaluate_processor_version" - }, - "description": "Sample for EvaluateProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_EvaluateProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_evaluate_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.fetch_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "FetchProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.FetchProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.FetchProcessorTypesResponse", - "shortName": "fetch_processor_types" - }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_fetch_processor_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_FetchProcessorTypes_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_fetch_processor_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.fetch_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.FetchProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "FetchProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.FetchProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.FetchProcessorTypesResponse", - "shortName": "fetch_processor_types" - }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_FetchProcessorTypes_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_fetch_processor_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_evaluation", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetEvaluationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Evaluation", - "shortName": "get_evaluation" - }, - "description": "Sample for GetEvaluation", - "file": "documentai_v1_generated_document_processor_service_get_evaluation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetEvaluation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_evaluation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_evaluation", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetEvaluation", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetEvaluationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Evaluation", - "shortName": "get_evaluation" - }, - "description": "Sample for GetEvaluation", - "file": "documentai_v1_generated_document_processor_service_get_evaluation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetEvaluation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_evaluation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_type", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1_generated_document_processor_service_get_processor_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_processor_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_type", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1_generated_document_processor_service_get_processor_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorType_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_processor_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.ProcessorVersion", - "shortName": "get_processor_version" - }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_get_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.ProcessorVersion", - "shortName": "get_processor_version" - }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessorVersion_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "get_processor" - }, - "description": "Sample for GetProcessor", - "file": "documentai_v1_generated_document_processor_service_get_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.GetProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.Processor", - "shortName": "get_processor" - }, - "description": "Sample for GetProcessor", - "file": "documentai_v1_generated_document_processor_service_get_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_GetProcessor_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_get_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListEvaluationsAsyncPager", - "shortName": "list_evaluations" - }, - "description": "Sample for ListEvaluations", - "file": "documentai_v1_generated_document_processor_service_list_evaluations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_evaluations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListEvaluationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListEvaluationsPager", - "shortName": "list_evaluations" - }, - "description": "Sample for ListEvaluations", - "file": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListEvaluations_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_evaluations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorTypesAsyncPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_list_processor_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorTypesPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1_generated_document_processor_service_list_processor_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1_generated_document_processor_service_list_processor_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorVersionsPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1_generated_document_processor_service_list_processor_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessorVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processor_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorsAsyncPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1_generated_document_processor_service_list_processors_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessors_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processors_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ListProcessorsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.services.document_processor_service.pagers.ListProcessorsPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1_generated_document_processor_service_list_processors_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ListProcessors_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_list_processors_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1_generated_document_processor_service_process_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ProcessDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_process_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1.types.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1_generated_document_processor_service_process_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ProcessDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_process_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1_generated_document_processor_service_review_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ReviewDocument_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_review_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1_generated_document_processor_service_review_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_ReviewDocument_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_review_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_set_default_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_set_default_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.SetDefaultProcessorVersionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_set_default_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.train_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "TrainProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor_version", - "type": "google.cloud.documentai_v1.types.ProcessorVersion" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "train_processor_version" - }, - "description": "Sample for TrainProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_train_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_TrainProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_train_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.train_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.TrainProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "TrainProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.TrainProcessorVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor_version", - "type": "google.cloud.documentai_v1.types.ProcessorVersion" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "train_processor_version" - }, - "description": "Sample for TrainProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_train_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_TrainProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_train_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceAsyncClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.UndeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_undeploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1.DocumentProcessorServiceClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1.types.UndeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1_generated_DocumentProcessorService_UndeployProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1_generated_document_processor_service_undeploy_processor_version_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-documentai/v1/scripts/fixup_documentai_v1_keywords.py b/owl-bot-staging/google-cloud-documentai/v1/scripts/fixup_documentai_v1_keywords.py deleted file mode 100644 index 022c18fa1d3e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/scripts/fixup_documentai_v1_keywords.py +++ /dev/null @@ -1,197 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', 'process_options', 'labels', ), - 'create_processor': ('parent', 'processor', ), - 'delete_processor': ('name', ), - 'delete_processor_version': ('name', ), - 'deploy_processor_version': ('name', ), - 'disable_processor': ('name', ), - 'enable_processor': ('name', ), - 'evaluate_processor_version': ('processor_version', 'evaluation_documents', ), - 'fetch_processor_types': ('parent', ), - 'get_evaluation': ('name', ), - 'get_processor': ('name', ), - 'get_processor_type': ('name', ), - 'get_processor_version': ('name', ), - 'list_evaluations': ('parent', 'page_size', 'page_token', ), - 'list_processors': ('parent', 'page_size', 'page_token', ), - 'list_processor_types': ('parent', 'page_size', 'page_token', ), - 'list_processor_versions': ('parent', 'page_size', 'page_token', ), - 'process_document': ('name', 'inline_document', 'raw_document', 'gcs_document', 'skip_human_review', 'field_mask', 'process_options', 'labels', ), - 'review_document': ('human_review_config', 'inline_document', 'enable_schema_validation', 'priority', 'document_schema', ), - 'set_default_processor_version': ('processor', 'default_processor_version', ), - 'train_processor_version': ('parent', 'processor_version', 'custom_document_extraction_options', 'document_schema', 'input_data', 'base_processor_version', ), - 'undeploy_processor_version': ('name', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=documentaiCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the documentai client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-documentai/v1/setup.py b/owl-bot-staging/google-cloud-documentai/v1/setup.py deleted file mode 100644 index 11e72a1d001b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/setup.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re - -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 = None - -with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <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/google-cloud-python/tree/main/packages/google-cloud-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.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.7.txt deleted file mode 100644 index b8a550c73855..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1/tests/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1/tests/unit/gapic/documentai_v1/__init__.py b/owl-bot-staging/google-cloud-documentai/v1/tests/unit/gapic/documentai_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/tests/unit/gapic/documentai_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py b/owl-bot-staging/google-cloud-documentai/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py deleted file mode 100644 index a4565cb22790..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1/tests/unit/gapic/documentai_v1/test_document_processor_service.py +++ /dev/null @@ -1,13565 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.documentai_v1.services.document_processor_service import DocumentProcessorServiceAsyncClient -from google.cloud.documentai_v1.services.document_processor_service import DocumentProcessorServiceClient -from google.cloud.documentai_v1.services.document_processor_service import pagers -from google.cloud.documentai_v1.services.document_processor_service import transports -from google.cloud.documentai_v1.types import barcode -from google.cloud.documentai_v1.types import document -from google.cloud.documentai_v1.types import document_io -from google.cloud.documentai_v1.types import document_processor_service -from google.cloud.documentai_v1.types import document_schema -from google.cloud.documentai_v1.types import evaluation -from google.cloud.documentai_v1.types import geometry -from google.cloud.documentai_v1.types import processor -from google.cloud.documentai_v1.types import processor as gcd_processor -from google.cloud.documentai_v1.types import processor_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 - -def test__read_environment_variables(): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DocumentProcessorServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentProcessorServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert DocumentProcessorServiceClient._get_client_cert_source(None, False) is None - assert DocumentProcessorServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DocumentProcessorServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - 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_default_cert_source): - assert DocumentProcessorServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DocumentProcessorServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DocumentProcessorServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DocumentProcessorServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, default_universe, "always") == DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentProcessorServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentProcessorServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert DocumentProcessorServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DocumentProcessorServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DocumentProcessorServiceClient._get_universe_domain(None, None) == DocumentProcessorServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DocumentProcessorServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -def test_document_processor_service_client_get_transport_class(): - transport = DocumentProcessorServiceClient.get_transport_class() - available_transports = [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentProcessorServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentProcessorServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "true"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "false"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - DocumentProcessorServiceClient, DocumentProcessorServiceAsyncClient -]) -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceAsyncClient)) -def test_document_processor_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", None), -]) -def test_document_processor_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_processor_types(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - response = client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - client.get_processor_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - -@pytest.mark.asyncio -async def test_get_processor_type_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorTypeRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - )) - response = await client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -@pytest.mark.asyncio -async def test_get_processor_type_async_from_dict(): - await test_get_processor_type_async(request_type=dict) - - -def test_get_processor_type_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = processor_type.ProcessorType() - client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_processor_type_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - await client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_processor_type_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor_type( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_processor_type_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_type_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor_type( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_processor_type_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - client.list_processors() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - -@pytest.mark.asyncio -async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorsRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processors_async_from_dict(): - await test_list_processors_async(request_type=dict) - - -def test_list_processors_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorsResponse() - client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_processors_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - await client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_processors_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processors( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_processors_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processors_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processors( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_processors_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_pager(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processors(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) -def test_list_processors_pages(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processors(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_processors_async_pager(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processors(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, processor.Processor) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processors_async_pages(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_processors(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - client.get_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - -@pytest.mark.asyncio -async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_get_processor_async_from_dict(): - await test_get_processor_async(request_type=dict) - - -def test_get_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = processor.Processor() - client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - await client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_processor_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_processor_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_processor_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.TrainProcessorVersionRequest, - dict, -]) -def test_train_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.TrainProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_train_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - client.train_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.TrainProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_train_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.TrainProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.TrainProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_train_processor_version_async_from_dict(): - await test_train_processor_version_async(request_type=dict) - - -def test_train_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.TrainProcessorVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_train_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.TrainProcessorVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_train_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.train_processor_version( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor_version - mock_val = processor.ProcessorVersion(name='name_value') - assert arg == mock_val - - -def test_train_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.train_processor_version( - document_processor_service.TrainProcessorVersionRequest(), - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_train_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.train_processor_version( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor_version - mock_val = processor.ProcessorVersion(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_train_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.train_processor_version( - document_processor_service.TrainProcessorVersionRequest(), - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - model_type=processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE, - ) - 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 - assert response.model_type == processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE - - -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, - model_type=processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE, - )) - 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 - assert response.model_type == processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE - - -@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 = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_processor_versions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - client.delete_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_delete_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_version_async_from_dict(): - await test_delete_processor_version_async(request_type=dict) - - -def test_delete_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_deploy_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - client.deploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_deploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeployProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_deploy_processor_version_async_from_dict(): - await test_deploy_processor_version_async(request_type=dict) - - -def test_deploy_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_deploy_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_deploy_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.deploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_deploy_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_deploy_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.deploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_deploy_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undeploy_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - client.undeploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.UndeployProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async_from_dict(): - await test_undeploy_processor_version_async(request_type=dict) - - -def test_undeploy_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_undeploy_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_undeploy_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.undeploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_undeploy_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_undeploy_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.undeploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_undeploy_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - client.create_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - -@pytest.mark.asyncio -async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.CreateProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_create_processor_async_from_dict(): - await test_create_processor_async(request_type=dict) - - -def test_create_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = gcd_processor.Processor() - client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - await client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_processor_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - - -def test_create_processor_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_processor_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_processor_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - client.delete_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - -@pytest.mark.asyncio -async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_async_from_dict(): - await test_delete_processor_async(request_type=dict) - - -def test_delete_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_processor_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_processor_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_processor_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_processor_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_enable_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - client.enable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - -@pytest.mark.asyncio -async def test_enable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EnableProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_enable_processor_async_from_dict(): - await test_enable_processor_async(request_type=dict) - - -def test_enable_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_enable_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_disable_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - client.disable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - -@pytest.mark.asyncio -async def test_disable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DisableProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_disable_processor_async_from_dict(): - await test_disable_processor_async(request_type=dict) - - -def test_disable_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_disable_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_default_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - client.set_default_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_set_default_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_default_processor_version_async_from_dict(): - await test_set_default_processor_version_async(request_type=dict) - - -def test_set_default_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor=processor_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor=processor_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_review_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - client.review_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - -@pytest.mark.asyncio -async def test_review_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ReviewDocumentRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_review_document_async_from_dict(): - await test_review_document_async(request_type=dict) - - -def test_review_document_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_review_document_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -def test_review_document_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.review_document( - human_review_config='human_review_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - - -def test_review_document_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - -@pytest.mark.asyncio -async def test_review_document_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.review_document( - human_review_config='human_review_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_review_document_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EvaluateProcessorVersionRequest, - dict, -]) -def test_evaluate_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_evaluate_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - client.evaluate_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_evaluate_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EvaluateProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_evaluate_processor_version_async_from_dict(): - await test_evaluate_processor_version_async(request_type=dict) - - -def test_evaluate_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EvaluateProcessorVersionRequest() - - request.processor_version = 'processor_version_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor_version=processor_version_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_evaluate_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EvaluateProcessorVersionRequest() - - request.processor_version = 'processor_version_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor_version=processor_version_value', - ) in kw['metadata'] - - -def test_evaluate_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.evaluate_processor_version( - processor_version='processor_version_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].processor_version - mock_val = 'processor_version_value' - assert arg == mock_val - - -def test_evaluate_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.evaluate_processor_version( - document_processor_service.EvaluateProcessorVersionRequest(), - processor_version='processor_version_value', - ) - -@pytest.mark.asyncio -async def test_evaluate_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.evaluate_processor_version( - processor_version='processor_version_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].processor_version - mock_val = 'processor_version_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_evaluate_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.evaluate_processor_version( - document_processor_service.EvaluateProcessorVersionRequest(), - processor_version='processor_version_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetEvaluationRequest, - dict, -]) -def test_get_evaluation(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - ) - response = client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - - -def test_get_evaluation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - client.get_evaluation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetEvaluationRequest() - -@pytest.mark.asyncio -async def test_get_evaluation_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetEvaluationRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - )) - response = await client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - - -@pytest.mark.asyncio -async def test_get_evaluation_async_from_dict(): - await test_get_evaluation_async(request_type=dict) - - -def test_get_evaluation_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetEvaluationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - call.return_value = evaluation.Evaluation() - client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_evaluation_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetEvaluationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation.Evaluation()) - await client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_evaluation_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation.Evaluation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_evaluation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_evaluation_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_evaluation( - document_processor_service.GetEvaluationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_evaluation_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation.Evaluation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation.Evaluation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_evaluation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_evaluation_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_evaluation( - document_processor_service.GetEvaluationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListEvaluationsRequest, - dict, -]) -def test_list_evaluations(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_evaluations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - client.list_evaluations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListEvaluationsRequest() - -@pytest.mark.asyncio -async def test_list_evaluations_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListEvaluationsRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_evaluations_async_from_dict(): - await test_list_evaluations_async(request_type=dict) - - -def test_list_evaluations_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListEvaluationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - call.return_value = document_processor_service.ListEvaluationsResponse() - client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_evaluations_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListEvaluationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListEvaluationsResponse()) - await client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_evaluations_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListEvaluationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_evaluations( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_evaluations_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_evaluations( - document_processor_service.ListEvaluationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_evaluations_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListEvaluationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListEvaluationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_evaluations( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_evaluations_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_evaluations( - document_processor_service.ListEvaluationsRequest(), - parent='parent_value', - ) - - -def test_list_evaluations_pager(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_evaluations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in results) -def test_list_evaluations_pages(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_evaluations(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_evaluations_async_pager(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_evaluations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_evaluations_async_pages(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_evaluations(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ProcessRequest, - dict, -]) -def test_process_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.process_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - - -def test_process_document_rest_required_fields(request_type=document_processor_service.ProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.process_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_process_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.process_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_process_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_process_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_process_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ProcessRequest.pb(document_processor_service.ProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ProcessResponse.to_json(document_processor_service.ProcessResponse()) - - request = document_processor_service.ProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ProcessResponse() - - client.process_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_process_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.process_document(request) - - -def test_process_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.process_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}:process" % client.transport._host, args[1]) - - -def test_process_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - - -def test_process_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.BatchProcessRequest, - dict, -]) -def test_batch_process_documents_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_process_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_process_documents_rest_required_fields(request_type=document_processor_service.BatchProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_process_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_process_documents_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_process_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_process_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_batch_process_documents") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_batch_process_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.BatchProcessRequest.pb(document_processor_service.BatchProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.BatchProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_process_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_process_documents_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.BatchProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_process_documents(request) - - -def test_batch_process_documents_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_process_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}:batchProcess" % client.transport._host, args[1]) - - -def test_batch_process_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - - -def test_batch_process_documents_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.FetchProcessorTypesRequest, - dict, -]) -def test_fetch_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.fetch_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -def test_fetch_processor_types_rest_required_fields(request_type=document_processor_service.FetchProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.fetch_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.FetchProcessorTypesRequest.pb(document_processor_service.FetchProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.FetchProcessorTypesResponse.to_json(document_processor_service.FetchProcessorTypesResponse()) - - request = document_processor_service.FetchProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.FetchProcessorTypesResponse() - - client.fetch_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.FetchProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_processor_types(request) - - -def test_fetch_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.fetch_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}:fetchProcessorTypes" % client.transport._host, args[1]) - - -def test_fetch_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_fetch_processor_types_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorTypesRequest, - dict, -]) -def test_list_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_types_rest_required_fields(request_type=document_processor_service.ListProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorTypesRequest.pb(document_processor_service.ListProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorTypesResponse.to_json(document_processor_service.ListProcessorTypesResponse()) - - request = document_processor_service.ListProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorTypesResponse() - - client.list_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_types(request) - - -def test_list_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processorTypes" % client.transport._host, args[1]) - - -def test_list_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_list_processor_types_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processor_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor_type.ProcessorType) - for i in results) - - pages = list(client.list_processor_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_type(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_rest_required_fields(request_type=document_processor_service.GetProcessorTypeRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_type_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_type_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorTypeRequest.pb(document_processor_service.GetProcessorTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor_type.ProcessorType.to_json(processor_type.ProcessorType()) - - request = document_processor_service.GetProcessorTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor_type.ProcessorType() - - client.get_processor_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_type_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorTypeRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_type(request) - - -def test_get_processor_type_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processorTypes/*}" % client.transport._host, args[1]) - - -def test_get_processor_type_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -def test_get_processor_type_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processors(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_rest_required_fields(request_type=document_processor_service.ListProcessorsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processors(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processors_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processors._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processors_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processors") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorsRequest.pb(document_processor_service.ListProcessorsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorsResponse.to_json(document_processor_service.ListProcessorsResponse()) - - request = document_processor_service.ListProcessorsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorsResponse() - - client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processors(request) - - -def test_list_processors_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processors(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_list_processors_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processors(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) - - pages = list(client.list_processors(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_rest_required_fields(request_type=document_processor_service.GetProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorRequest.pb(document_processor_service.GetProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.Processor.to_json(processor.Processor()) - - request = document_processor_service.GetProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.Processor() - - client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor(request) - - -def test_get_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_get_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -def test_get_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.TrainProcessorVersionRequest, - dict, -]) -def test_train_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.train_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_train_processor_version_rest_required_fields(request_type=document_processor_service.TrainProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.train_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_train_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.train_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_train_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_train_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_train_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.TrainProcessorVersionRequest.pb(document_processor_service.TrainProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.TrainProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.train_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_train_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.TrainProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.train_processor_version(request) - - -def test_train_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.train_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions:train" % client.transport._host, args[1]) - - -def test_train_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.train_processor_version( - document_processor_service.TrainProcessorVersionRequest(), - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - -def test_train_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - model_type=processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - assert response.model_type == processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE - - -def test_get_processor_version_rest_required_fields(request_type=document_processor_service.GetProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorVersionRequest.pb(document_processor_service.GetProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.ProcessorVersion.to_json(processor.ProcessorVersion()) - - request = document_processor_service.GetProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.ProcessorVersion() - - client.get_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_version(request) - - -def test_get_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_get_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - - -def test_get_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorVersionsRequest, - dict, -]) -def test_list_processor_versions_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_versions_rest_required_fields(request_type=document_processor_service.ListProcessorVersionsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_versions_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_versions_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_versions") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorVersionsRequest.pb(document_processor_service.ListProcessorVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorVersionsResponse.to_json(document_processor_service.ListProcessorVersionsResponse()) - - request = document_processor_service.ListProcessorVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorVersionsResponse() - - client.list_processor_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_versions_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorVersionsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_versions(request) - - -def test_list_processor_versions_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*}/processorVersions" % client.transport._host, args[1]) - - -def test_list_processor_versions_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - - -def test_list_processor_versions_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorVersionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - pager = client.list_processor_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.ProcessorVersion) - for i in results) - - pages = list(client.list_processor_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_version_rest_required_fields(request_type=document_processor_service.DeleteProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorVersionRequest.pb(document_processor_service.DeleteProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor_version(request) - - -def test_delete_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_delete_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -def test_delete_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.deploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_deploy_processor_version_rest_required_fields(request_type=document_processor_service.DeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.deploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_deploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_deploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_deploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_deploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeployProcessorVersionRequest.pb(document_processor_service.DeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.deploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_deploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.deploy_processor_version(request) - - -def test_deploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.deploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" % client.transport._host, args[1]) - - -def test_deploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_deploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.undeploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_undeploy_processor_version_rest_required_fields(request_type=document_processor_service.UndeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.undeploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undeploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undeploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_undeploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_undeploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.UndeployProcessorVersionRequest.pb(document_processor_service.UndeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.UndeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undeploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undeploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.UndeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.undeploy_processor_version(request) - - -def test_undeploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.undeploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" % client.transport._host, args[1]) - - -def test_undeploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_undeploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'processor_version_aliases': [{'alias': 'alias_value', 'processor_version': 'processor_version_value'}], 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = document_processor_service.CreateProcessorRequest.meta.fields["processor"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["processor"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["processor"][field])): - del request_init["processor"][field][i][subfield] - else: - del request_init["processor"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_rest_required_fields(request_type=document_processor_service.CreateProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processor", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_create_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.CreateProcessorRequest.pb(document_processor_service.CreateProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_processor.Processor.to_json(gcd_processor.Processor()) - - request = document_processor_service.CreateProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_processor.Processor() - - client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.CreateProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_processor(request) - - -def test_create_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_create_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -def test_create_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_rest_required_fields(request_type=document_processor_service.DeleteProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorRequest.pb(document_processor_service.DeleteProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor(request) - - -def test_delete_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_delete_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -def test_delete_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.enable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_enable_processor_rest_required_fields(request_type=document_processor_service.EnableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.enable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_enable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.enable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EnableProcessorRequest.pb(document_processor_service.EnableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EnableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.enable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_enable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EnableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.enable_processor(request) - - -def test_enable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.disable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_disable_processor_rest_required_fields(request_type=document_processor_service.DisableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.disable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_disable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.disable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DisableProcessorRequest.pb(document_processor_service.DisableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DisableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.disable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_disable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DisableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.disable_processor(request) - - -def test_disable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_default_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_default_processor_version_rest_required_fields(request_type=document_processor_service.SetDefaultProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor"] = "" - request_init["default_processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processor"] = 'processor_value' - jsonified_request["defaultProcessorVersion"] = 'default_processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processor" in jsonified_request - assert jsonified_request["processor"] == 'processor_value' - assert "defaultProcessorVersion" in jsonified_request - assert jsonified_request["defaultProcessorVersion"] == 'default_processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_default_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_default_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_default_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processor", "defaultProcessorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_set_default_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_set_default_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb(document_processor_service.SetDefaultProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.SetDefaultProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_default_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_default_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_default_processor_version(request) - - -def test_set_default_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.review_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_review_document_rest_required_fields(request_type=document_processor_service.ReviewDocumentRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["human_review_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["humanReviewConfig"] = 'human_review_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "humanReviewConfig" in jsonified_request - assert jsonified_request["humanReviewConfig"] == 'human_review_config_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.review_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_review_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.review_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("humanReviewConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_review_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_review_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_review_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ReviewDocumentRequest.pb(document_processor_service.ReviewDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.ReviewDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.review_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_review_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ReviewDocumentRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.review_document(request) - - -def test_review_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - - # get truthy value for each flattened field - mock_args = dict( - human_review_config='human_review_config_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.review_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" % client.transport._host, args[1]) - - -def test_review_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -def test_review_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EvaluateProcessorVersionRequest, - dict, -]) -def test_evaluate_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.evaluate_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_evaluate_processor_version_rest_required_fields(request_type=document_processor_service.EvaluateProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processorVersion"] = 'processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processorVersion" in jsonified_request - assert jsonified_request["processorVersion"] == 'processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.evaluate_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_evaluate_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.evaluate_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_evaluate_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_evaluate_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_evaluate_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EvaluateProcessorVersionRequest.pb(document_processor_service.EvaluateProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EvaluateProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.evaluate_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_evaluate_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EvaluateProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.evaluate_processor_version(request) - - -def test_evaluate_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - processor_version='processor_version_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.evaluate_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion" % client.transport._host, args[1]) - - -def test_evaluate_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.evaluate_processor_version( - document_processor_service.EvaluateProcessorVersionRequest(), - processor_version='processor_version_value', - ) - - -def test_evaluate_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetEvaluationRequest, - dict, -]) -def test_get_evaluation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_evaluation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - - -def test_get_evaluation_rest_required_fields(request_type=document_processor_service.GetEvaluationRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_evaluation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_evaluation_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_evaluation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_evaluation_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_evaluation") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_evaluation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetEvaluationRequest.pb(document_processor_service.GetEvaluationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = evaluation.Evaluation.to_json(evaluation.Evaluation()) - - request = document_processor_service.GetEvaluationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = evaluation.Evaluation() - - client.get_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_evaluation_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetEvaluationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_evaluation(request) - - -def test_get_evaluation_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_evaluation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}" % client.transport._host, args[1]) - - -def test_get_evaluation_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_evaluation( - document_processor_service.GetEvaluationRequest(), - name='name_value', - ) - - -def test_get_evaluation_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListEvaluationsRequest, - dict, -]) -def test_list_evaluations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_evaluations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_evaluations_rest_required_fields(request_type=document_processor_service.ListEvaluationsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_evaluations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_evaluations_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_evaluations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_evaluations_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_evaluations") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_evaluations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListEvaluationsRequest.pb(document_processor_service.ListEvaluationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListEvaluationsResponse.to_json(document_processor_service.ListEvaluationsResponse()) - - request = document_processor_service.ListEvaluationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListEvaluationsResponse() - - client.list_evaluations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_evaluations_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListEvaluationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_evaluations(request) - - -def test_list_evaluations_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_evaluations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations" % client.transport._host, args[1]) - - -def test_list_evaluations_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_evaluations( - document_processor_service.ListEvaluationsRequest(), - parent='parent_value', - ) - - -def test_list_evaluations_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListEvaluationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - pager = client.list_evaluations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in results) - - pages = list(client.list_evaluations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentProcessorServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentProcessorServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentProcessorServiceGrpcTransport, - ) - -def test_document_processor_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_processor_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'process_document', - 'batch_process_documents', - 'fetch_processor_types', - 'list_processor_types', - 'get_processor_type', - 'list_processors', - 'get_processor', - 'train_processor_version', - 'get_processor_version', - 'list_processor_versions', - 'delete_processor_version', - 'deploy_processor_version', - 'undeploy_processor_version', - 'create_processor', - 'delete_processor', - 'enable_processor', - 'disable_processor', - 'set_default_processor_version', - 'review_document', - 'evaluate_processor_version', - 'get_evaluation', - 'list_evaluations', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_document_processor_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_document_processor_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport() - adc.assert_called_once() - - -def test_document_processor_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentProcessorServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - ], -) -def test_document_processor_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, - ], -) -def test_document_processor_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentProcessorServiceGrpcTransport, grpc_helpers), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_processor_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_document_processor_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DocumentProcessorServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_processor_service_rest_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_no_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_with_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_processor_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentProcessorServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentProcessorServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.process_document._session - session2 = client2.transport.process_document._session - assert session1 != session2 - session1 = client1.transport.batch_process_documents._session - session2 = client2.transport.batch_process_documents._session - assert session1 != session2 - session1 = client1.transport.fetch_processor_types._session - session2 = client2.transport.fetch_processor_types._session - assert session1 != session2 - session1 = client1.transport.list_processor_types._session - session2 = client2.transport.list_processor_types._session - assert session1 != session2 - session1 = client1.transport.get_processor_type._session - session2 = client2.transport.get_processor_type._session - assert session1 != session2 - session1 = client1.transport.list_processors._session - session2 = client2.transport.list_processors._session - assert session1 != session2 - session1 = client1.transport.get_processor._session - session2 = client2.transport.get_processor._session - assert session1 != session2 - session1 = client1.transport.train_processor_version._session - session2 = client2.transport.train_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_processor_version._session - session2 = client2.transport.get_processor_version._session - assert session1 != session2 - session1 = client1.transport.list_processor_versions._session - session2 = client2.transport.list_processor_versions._session - assert session1 != session2 - session1 = client1.transport.delete_processor_version._session - session2 = client2.transport.delete_processor_version._session - assert session1 != session2 - session1 = client1.transport.deploy_processor_version._session - session2 = client2.transport.deploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.undeploy_processor_version._session - session2 = client2.transport.undeploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.create_processor._session - session2 = client2.transport.create_processor._session - assert session1 != session2 - session1 = client1.transport.delete_processor._session - session2 = client2.transport.delete_processor._session - assert session1 != session2 - session1 = client1.transport.enable_processor._session - session2 = client2.transport.enable_processor._session - assert session1 != session2 - session1 = client1.transport.disable_processor._session - session2 = client2.transport.disable_processor._session - assert session1 != session2 - session1 = client1.transport.set_default_processor_version._session - session2 = client2.transport.set_default_processor_version._session - assert session1 != session2 - session1 = client1.transport.review_document._session - session2 = client2.transport.review_document._session - assert session1 != session2 - session1 = client1.transport.evaluate_processor_version._session - session2 = client2.transport.evaluate_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_evaluation._session - session2 = client2.transport.get_evaluation._session - assert session1 != session2 - session1 = client1.transport.list_evaluations._session - session2 = client2.transport.list_evaluations._session - assert session1 != session2 -def test_document_processor_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_document_processor_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_document_processor_service_grpc_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_document_processor_service_grpc_lro_async_client(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_evaluation_path(): - project = "squid" - location = "clam" - processor = "whelk" - processor_version = "octopus" - evaluation = "oyster" - expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}".format(project=project, location=location, processor=processor, processor_version=processor_version, evaluation=evaluation, ) - actual = DocumentProcessorServiceClient.evaluation_path(project, location, processor, processor_version, evaluation) - assert expected == actual - - -def test_parse_evaluation_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "processor": "mussel", - "processor_version": "winkle", - "evaluation": "nautilus", - } - path = DocumentProcessorServiceClient.evaluation_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_evaluation_path(path) - assert expected == actual - -def test_human_review_config_path(): - project = "scallop" - location = "abalone" - processor = "squid" - expected = "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) - actual = DocumentProcessorServiceClient.human_review_config_path(project, location, processor) - assert expected == actual - - -def test_parse_human_review_config_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor": "octopus", - } - path = DocumentProcessorServiceClient.human_review_config_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_human_review_config_path(path) - assert expected == actual - -def test_processor_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - actual = DocumentProcessorServiceClient.processor_path(project, location, processor) - assert expected == actual - - -def test_parse_processor_path(): - expected = { - "project": "mussel", - "location": "winkle", - "processor": "nautilus", - } - path = DocumentProcessorServiceClient.processor_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_path(path) - assert expected == actual - -def test_processor_type_path(): - project = "scallop" - location = "abalone" - processor_type = "squid" - expected = "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - actual = DocumentProcessorServiceClient.processor_type_path(project, location, processor_type) - assert expected == actual - - -def test_parse_processor_type_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor_type": "octopus", - } - path = DocumentProcessorServiceClient.processor_type_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_type_path(path) - assert expected == actual - -def test_processor_version_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - processor_version = "mussel" - expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - actual = DocumentProcessorServiceClient.processor_version_path(project, location, processor, processor_version) - assert expected == actual - - -def test_parse_processor_version_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "processor": "scallop", - "processor_version": "abalone", - } - path = DocumentProcessorServiceClient.processor_version_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentProcessorServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DocumentProcessorServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentProcessorServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DocumentProcessorServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentProcessorServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DocumentProcessorServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DocumentProcessorServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DocumentProcessorServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentProcessorServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DocumentProcessorServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentProcessorServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_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 = 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_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 = 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_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 = 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_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.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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/google-cloud-documentai/v1beta2/.coveragerc b/owl-bot-staging/google-cloud-documentai/v1beta2/.coveragerc deleted file mode 100644 index 46ab6093e34b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/documentai/__init__.py - google/cloud/documentai/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/.flake8 b/owl-bot-staging/google-cloud-documentai/v1beta2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/MANIFEST.in b/owl-bot-staging/google-cloud-documentai/v1beta2/MANIFEST.in deleted file mode 100644 index cd0fd7a84761..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/documentai *.py -recursive-include google/cloud/documentai_v1beta2 *.py diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/README.rst b/owl-bot-staging/google-cloud-documentai/v1beta2/README.rst deleted file mode 100644 index 484a3c1c8fa7..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Documentai API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Documentai API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/_static/custom.css b/owl-bot-staging/google-cloud-documentai/v1beta2/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/conf.py b/owl-bot-staging/google-cloud-documentai/v1beta2/docs/conf.py deleted file mode 100644 index 8d93c59cdbb8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2023, 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 = 'en' - -# 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/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst b/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst deleted file mode 100644 index a0d0da7e3c88..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/document_understanding_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -DocumentUnderstandingService ----------------------------------------------- - -.. automodule:: google.cloud.documentai_v1beta2.services.document_understanding_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/services_.rst b/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/services_.rst deleted file mode 100644 index 13f4a238f1af..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Documentai v1beta2 API -================================================ -.. toctree:: - :maxdepth: 2 - - document_understanding_service diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/types_.rst b/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/types_.rst deleted file mode 100644 index 35540dd05728..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/documentai_v1beta2/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Documentai v1beta2 API -============================================= - -.. automodule:: google.cloud.documentai_v1beta2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/index.rst b/owl-bot-staging/google-cloud-documentai/v1beta2/docs/index.rst deleted file mode 100644 index 38d5fbb50123..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - documentai_v1beta2/services - documentai_v1beta2/types diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/__init__.py deleted file mode 100644 index ca826cc1a737..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/__init__.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.barcode import Barcode -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', - 'Barcode', - '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/google-cloud-documentai/v1beta2/google/cloud/documentai/gapic_version.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/py.typed b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/py.typed deleted file mode 100644 index 81b450017987..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/__init__.py deleted file mode 100644 index 27fb0f418c44..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/__init__.py +++ /dev/null @@ -1,70 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.documentai_v1beta2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.document_understanding_service import DocumentUnderstandingServiceClient -from .services.document_understanding_service import DocumentUnderstandingServiceAsyncClient - -from .types.barcode import Barcode -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', -'Barcode', -'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/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json deleted file mode 100644 index 633dcc19c472..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/gapic_metadata.json +++ /dev/null @@ -1,43 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.documentai_v1beta2", - "protoPackage": "google.cloud.documentai.v1beta2", - "schema": "1.0", - "services": { - "DocumentUnderstandingService": { - "clients": { - "grpc": { - "libraryClient": "DocumentUnderstandingServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentUnderstandingServiceAsyncClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/py.typed b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/py.typed deleted file mode 100644 index 81b450017987..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py deleted file mode 100644 index bb728d8be53c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py deleted file mode 100644 index 51589e33af74..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/async_client.py +++ /dev/null @@ -1,740 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.documentai_v1beta2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -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 - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DocumentUnderstandingServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentUnderstandingServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DocumentUnderstandingServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DocumentUnderstandingServiceClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(DocumentUnderstandingServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentUnderstandingServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentUnderstandingServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentUnderstandingServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentUnderstandingServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentUnderstandingServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentUnderstandingServiceAsyncClient: The constructed client. - """ - return DocumentUnderstandingServiceClient.from_service_account_info.__func__(DocumentUnderstandingServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentUnderstandingServiceAsyncClient: The constructed client. - """ - return DocumentUnderstandingServiceClient.from_service_account_file.__func__(DocumentUnderstandingServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentUnderstandingServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentUnderstandingServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentUnderstandingServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = functools.partial(type(DocumentUnderstandingServiceClient).get_transport_class, type(DocumentUnderstandingServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentUnderstandingServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document understanding service async 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. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = DocumentUnderstandingServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def batch_process_documents(self, - request: Optional[Union[document_understanding.BatchProcessDocumentsRequest, dict]] = None, - *, - requests: Optional[MutableSequence[document_understanding.ProcessDocumentRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta2 - - async def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() - - # Initialize request argument(s) - requests = documentai_v1beta2.ProcessDocumentRequest() - requests.input_config.gcs_source.uri = "uri_value" - requests.input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.BatchProcessDocumentsRequest( - requests=requests, - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest, dict]]): - The request object. Request to batch process documents as an asynchronous - operation. The output is written to Cloud Storage as - JSON in the [Document] format. - requests (:class:`MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]`): - Required. Individual requests for - each document. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.AsyncRetry( -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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_understanding.BatchProcessDocumentsResponse, - metadata_type=document_understanding.OperationMetadata, - ) - - # Done; return the response. - return response - - async def process_document(self, - request: Optional[Union[document_understanding.ProcessDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Processes a single document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta2 - - async def sample_process_document(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceAsyncClient() - - # Initialize request argument(s) - input_config = documentai_v1beta2.InputConfig() - input_config.gcs_source.uri = "uri_value" - input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.ProcessDocumentRequest( - input_config=input_config, - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest, dict]]): - The request object. Request to process one document. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 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. - - """ - # 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.AsyncRetry( -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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DocumentUnderstandingServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentUnderstandingServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py deleted file mode 100644 index 19992da85952..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/client.py +++ /dev/null @@ -1,1063 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.documentai_v1beta2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentUnderstandingServiceGrpcTransport -from .transports.grpc_asyncio import DocumentUnderstandingServiceGrpcAsyncIOTransport - - -class DocumentUnderstandingServiceClientMeta(type): - """Metaclass for the DocumentUnderstandingService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentUnderstandingServiceTransport]] - _transport_registry["grpc"] = DocumentUnderstandingServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentUnderstandingServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentUnderstandingServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentUnderstandingServiceClient(metaclass=DocumentUnderstandingServiceClientMeta): - """Service to parse structured information from unstructured or - semi-structured documents using state-of-the-art Google AI such - as natural language, computer vision, and translation. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "documentai.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "documentai.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - 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 - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - 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`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = DocumentUnderstandingServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DocumentUnderstandingServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DocumentUnderstandingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = DocumentUnderstandingServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DocumentUnderstandingServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DocumentUnderstandingServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentUnderstandingServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document understanding service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DocumentUnderstandingServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = DocumentUnderstandingServiceClient._read_environment_variables() - self._client_cert_source = DocumentUnderstandingServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DocumentUnderstandingServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._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. - transport_provided = isinstance(transport, DocumentUnderstandingServiceTransport) - if transport_provided: - # transport is a DocumentUnderstandingServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(DocumentUnderstandingServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DocumentUnderstandingServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - 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(cast(str, transport)) - self._transport = Transport( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def batch_process_documents(self, - request: Optional[Union[document_understanding.BatchProcessDocumentsRequest, dict]] = None, - *, - requests: Optional[MutableSequence[document_understanding.ProcessDocumentRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta2 - - def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceClient() - - # Initialize request argument(s) - requests = documentai_v1beta2.ProcessDocumentRequest() - requests.input_config.gcs_source.uri = "uri_value" - requests.input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.BatchProcessDocumentsRequest( - requests=requests, - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest, dict]): - The request object. Request to batch process documents as an asynchronous - operation. The output is written to Cloud Storage as - JSON in the [Document] format. - requests (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]): - Required. Individual requests for - each document. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1beta2.types.BatchProcessDocumentsResponse` Response to an batch document processing request. This is returned in - the LRO Operation after the operation is complete. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([requests]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_understanding.BatchProcessDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_understanding.BatchProcessDocumentsRequest): - request = document_understanding.BatchProcessDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if requests is not None: - request.requests = requests - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_process_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_understanding.BatchProcessDocumentsResponse, - metadata_type=document_understanding.OperationMetadata, - ) - - # Done; return the response. - return response - - def process_document(self, - request: Optional[Union[document_understanding.ProcessDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Processes a single document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta2 - - def sample_process_document(): - # Create a client - client = documentai_v1beta2.DocumentUnderstandingServiceClient() - - # Initialize request argument(s) - input_config = documentai_v1beta2.InputConfig() - input_config.gcs_source.uri = "uri_value" - input_config.mime_type = "mime_type_value" - - request = documentai_v1beta2.ProcessDocumentRequest( - input_config=input_config, - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest, dict]): - The request object. Request to process one document. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta2.types.Document: - Document represents the canonical - document resource in Document 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. - - """ - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentUnderstandingServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentUnderstandingServiceClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py deleted file mode 100644 index 4623f79d08fe..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py deleted file mode 100644 index 00665a7a5587..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/base.py +++ /dev/null @@ -1,232 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.documentai_v1beta2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.documentai_v1beta2.types import document -from google.cloud.documentai_v1beta2.types import document_understanding -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentUnderstandingServiceTransport(abc.ABC): - """Abstract transport class for DocumentUnderstandingService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'documentai.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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 - - @property - def host(self): - return self._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 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__ = ( - 'DocumentUnderstandingServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py deleted file mode 100644 index 54d7b8622bef..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc.py +++ /dev/null @@ -1,404 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentUnderstandingServiceGrpcTransport(DocumentUnderstandingServiceTransport): - """gRPC backend transport for DocumentUnderstandingService. - - Service to parse structured information from unstructured or - semi-structured documents using state-of-the-art Google AI such - as natural language, computer vision, and translation. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def batch_process_documents(self) -> Callable[ - [document_understanding.BatchProcessDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/BatchProcessDocuments', - request_serializer=document_understanding.BatchProcessDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def process_document(self) -> Callable[ - [document_understanding.ProcessDocumentRequest], - document.Document]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta2.DocumentUnderstandingService/ProcessDocument', - request_serializer=document_understanding.ProcessDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['process_document'] - - def close(self): - self.grpc_channel.close() - - @property - def 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__ = ( - 'DocumentUnderstandingServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py deleted file mode 100644 index 08c05284bd65..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/services/document_understanding_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,403 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentUnderstandingServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentUnderstandingServiceGrpcTransport - - -class DocumentUnderstandingServiceGrpcAsyncIOTransport(DocumentUnderstandingServiceTransport): - """gRPC AsyncIO backend transport for DocumentUnderstandingService. - - Service to parse structured information from unstructured or - semi-structured documents using state-of-the-art Google AI such - as natural language, computer vision, and translation. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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() - - @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__ = ( - 'DocumentUnderstandingServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py deleted file mode 100644 index b7ad9d9fcbbc..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/__init__.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_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__ = ( - 'Barcode', - '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/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/barcode.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/barcode.py deleted file mode 100644 index 3157967ea1bd..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/barcode.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta2', - manifest={ - 'Barcode', - }, -) - - -class Barcode(proto.Message): - r"""Encodes the detailed information of a barcode. - - Attributes: - format_ (str): - Format of a barcode. The supported formats are: - - - ``CODE_128``: Code 128 type. - - ``CODE_39``: Code 39 type. - - ``CODE_93``: Code 93 type. - - ``CODABAR``: Codabar type. - - ``DATA_MATRIX``: 2D Data Matrix type. - - ``ITF``: ITF type. - - ``EAN_13``: EAN-13 type. - - ``EAN_8``: EAN-8 type. - - ``QR_CODE``: 2D QR code type. - - ``UPC_A``: UPC-A type. - - ``UPC_E``: UPC-E type. - - ``PDF417``: PDF417 type. - - ``AZTEC``: 2D Aztec code type. - - ``DATABAR``: GS1 DataBar code type. - value_format (str): - Value format describes the format of the value that a - barcode encodes. The supported formats are: - - - ``CONTACT_INFO``: Contact information. - - ``EMAIL``: Email address. - - ``ISBN``: ISBN identifier. - - ``PHONE``: Phone number. - - ``PRODUCT``: Product. - - ``SMS``: SMS message. - - ``TEXT``: Text string. - - ``URL``: URL address. - - ``WIFI``: Wifi information. - - ``GEO``: Geo-localization. - - ``CALENDAR_EVENT``: Calendar event. - - ``DRIVER_LICENSE``: Driver's license. - raw_value (str): - Raw value encoded in the barcode. For example: - ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. - """ - - format_: str = proto.Field( - proto.STRING, - number=1, - ) - value_format: str = proto.Field( - proto.STRING, - number=2, - ) - raw_value: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/document.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/document.py deleted file mode 100644 index 24f4f0ced985..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/document.py +++ /dev/null @@ -1,1887 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1beta2.types import barcode as gcd_barcode -from google.cloud.documentai_v1beta2.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.v1beta2', - 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. For more information, refer to `Google Cloud - Storage Request - URIs `__. - - 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 `media type (MIME - type) `__. - text (str): - Optional. UTF-8 encoded text in reading order - from the document. - text_styles (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Style]): - Styles for the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - pages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page]): - Visual page layout for the - [Document][google.cloud.documentai.v1beta2.Document]. - entities (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Entity]): - A list of entities detected on - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - For document shards, entities in this list may cross shard - boundaries. - entity_relations (MutableSequence[google.cloud.documentai_v1beta2.types.Document.EntityRelation]): - Placeholder. Relationship among - [Document.entities][google.cloud.documentai.v1beta2.Document.entities]. - text_changes (MutableSequence[google.cloud.documentai_v1beta2.types.Document.TextChange]): - Placeholder. A list of text corrections made to - [Document.text][google.cloud.documentai.v1beta2.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_v1beta2.types.Document.ShardInfo): - Information about the sharding if this - document is sharded part of a larger document. - If the document is not sharded, this message is - not specified. - labels (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Label]): - [Label][google.cloud.documentai.v1beta2.Document.Label]s for - this document. - error (google.rpc.status_pb2.Status): - Any error that occurred while processing this - document. - revisions (MutableSequence[google.cloud.documentai_v1beta2.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.v1beta2.Document.text] - in the overall document global text. - """ - - shard_index: int = proto.Field( - proto.INT64, - number=1, - ) - shard_count: int = proto.Field( - proto.INT64, - number=2, - ) - text_offset: int = proto.Field( - proto.INT64, - number=3, - ) - - class Label(proto.Message): - r"""Label attaches schema information and/or other metadata to segments - within a [Document][google.cloud.documentai.v1beta2.Document]. - Multiple [Label][google.cloud.documentai.v1beta2.Document.Label]s on - a single field can denote either different labels, different - instances of the same label created at different times, or some - combination of both. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - automl_model (str): - Label is generated AutoML model. This field stores the full - resource name of the AutoML model. - - Format: - ``projects/{project-id}/locations/{location-id}/models/{model-id}`` - - This field is a member of `oneof`_ ``source``. - name (str): - Name of the label. - - When the label is generated from AutoML Text - Classification model, this field represents the - name of the category. - confidence (float): - Confidence score between 0 and 1 for label - assignment. - """ - - automl_model: str = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=3, - ) - - class Style(proto.Message): - r"""Annotation for common text style attributes. This adheres to - CSS conventions as much as possible. - - Attributes: - text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - color (google.type.color_pb2.Color): - Text color. - background_color (google.type.color_pb2.Color): - Text background color. - font_weight (str): - `Font - weight `__. - Possible values are ``normal``, ``bold``, ``bolder``, and - ``lighter``. - text_style (str): - `Text - style `__. - Possible values are ``normal``, ``italic``, and ``oblique``. - text_decoration (str): - `Text - decoration `__. - Follows CSS standard. - font_size (google.cloud.documentai_v1beta2.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 (such as ``in``, - ``px``, and ``pt``). - """ - - size: float = proto.Field( - proto.FLOAT, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=2, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=3, - message=color_pb2.Color, - ) - font_weight: str = proto.Field( - proto.STRING, - number=4, - ) - text_style: str = proto.Field( - proto.STRING, - number=5, - ) - text_decoration: str = proto.Field( - proto.STRING, - number=6, - ) - font_size: 'Document.Style.FontSize' = proto.Field( - proto.MESSAGE, - number=7, - message='Document.Style.FontSize', - ) - font_family: str = proto.Field( - proto.STRING, - number=8, - ) - - class Page(proto.Message): - r"""A page in a [Document][google.cloud.documentai.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. - image (google.cloud.documentai_v1beta2.types.Document.Page.Image): - Rendered image for this page. This image is - preprocessed to remove any skew, rotation, and - distortions such that the annotation bounding - boxes can be upright and axis-aligned. - transforms (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Matrix]): - Transformation matrices that were applied to the original - document image to produce - [Page.image][google.cloud.documentai.v1beta2.Document.Page.image]. - dimension (google.cloud.documentai_v1beta2.types.Document.Page.Dimension): - Physical dimension of the page. - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for the page. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - blocks (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Block]): - A list of visually detected text blocks on - the page. A block has a set of lines (collected - into paragraphs) that have a common line-spacing - and orientation. - paragraphs (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Paragraph]): - A list of visually detected text paragraphs - on the page. A collection of lines that a human - would perceive as a paragraph. - lines (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Line]): - A list of visually detected text lines on the - page. A collection of tokens that a human would - perceive as a line. - tokens (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Token]): - A list of visually detected tokens on the - page. - visual_elements (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.VisualElement]): - A list of detected non-text visual elements - e.g. checkbox, signature etc. on the page. - tables (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table]): - A list of visually detected tables on the - page. - form_fields (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.FormField]): - A list of visually detected form fields on - the page. - symbols (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Symbol]): - A list of visually detected symbols on the - page. - detected_barcodes (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedBarcode]): - A list of detected barcodes. - image_quality_scores (google.cloud.documentai_v1beta2.types.Document.Page.ImageQualityScores): - Image quality scores. - provenance (google.cloud.documentai_v1beta2.types.Document.Provenance): - The history of this page. - """ - - class Dimension(proto.Message): - r"""Dimension for the page. - - Attributes: - width (float): - Page width. - height (float): - Page height. - unit (str): - Dimension unit. - """ - - width: float = proto.Field( - proto.FLOAT, - number=1, - ) - height: float = proto.Field( - proto.FLOAT, - number=2, - ) - unit: str = proto.Field( - proto.STRING, - number=3, - ) - - class Image(proto.Message): - r"""Rendered image contents for this page. - - Attributes: - content (bytes): - Raw byte content of the image. - mime_type (str): - Encoding `media type (MIME - type) `__ - for the image. - width (int): - Width of the image in pixels. - height (int): - Height of the image in pixels. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - width: int = proto.Field( - proto.INT32, - number=3, - ) - height: int = proto.Field( - proto.INT32, - number=4, - ) - - class Matrix(proto.Message): - r"""Representation for transformation matrix, intended to be - compatible and used with OpenCV format for image manipulation. - - Attributes: - rows (int): - Number of rows in the matrix. - cols (int): - Number of columns in the matrix. - type_ (int): - This encodes information about what data type the matrix - uses. For example, 0 (CV_8U) is an unsigned 8-bit image. For - the full list of OpenCV primitive data types, please refer - to - https://docs.opencv.org/4.3.0/d1/d1b/group__core__hal__interface.html - data (bytes): - The matrix data. - """ - - rows: int = proto.Field( - proto.INT32, - number=1, - ) - cols: int = proto.Field( - proto.INT32, - number=2, - ) - type_: int = proto.Field( - proto.INT32, - number=3, - ) - data: bytes = proto.Field( - proto.BYTES, - number=4, - ) - - class Layout(proto.Message): - r"""Visual element describing a layout unit on a page. - - Attributes: - text_anchor (google.cloud.documentai_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]. - """ - class Orientation(proto.Enum): - r"""Detected human reading orientation. - - Values: - ORIENTATION_UNSPECIFIED (0): - Unspecified orientation. - PAGE_UP (1): - Orientation is aligned with page up. - PAGE_RIGHT (2): - Orientation is aligned with page right. - Turn the head 90 degrees clockwise from upright - to read. - PAGE_DOWN (3): - Orientation is aligned with page down. - Turn the head 180 degrees from upright to read. - PAGE_LEFT (4): - Orientation is aligned with page left. - Turn the head 90 degrees counterclockwise from - upright to read. - """ - ORIENTATION_UNSPECIFIED = 0 - PAGE_UP = 1 - PAGE_RIGHT = 2 - PAGE_DOWN = 3 - PAGE_LEFT = 4 - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=3, - message=geometry.BoundingPoly, - ) - orientation: 'Document.Page.Layout.Orientation' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Page.Layout.Orientation', - ) - - class Block(proto.Message): - r"""A block has a set of lines (collected into paragraphs) that - have a common line-spacing and orientation. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Block][google.cloud.documentai.v1beta2.Document.Page.Block]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta2.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Paragraph(proto.Message): - r"""A collection of lines that a human would perceive as a - paragraph. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Paragraph][google.cloud.documentai.v1beta2.Document.Page.Paragraph]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta2.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Line(proto.Message): - r"""A collection of tokens that a human would perceive as a line. - Does not cross column boundaries, can be horizontal, vertical, - etc. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Line][google.cloud.documentai.v1beta2.Document.Page.Line]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta2.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Token(proto.Message): - r"""A detected token. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. - detected_break (google.cloud.documentai_v1beta2.types.Document.Page.Token.DetectedBreak): - Detected break at the end of a - [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta2.types.Document.Provenance): - The history of this annotation. - style_info (google.cloud.documentai_v1beta2.types.Document.Page.Token.StyleInfo): - Text style attributes. - """ - - class DetectedBreak(proto.Message): - r"""Detected break at the end of a - [Token][google.cloud.documentai.v1beta2.Document.Page.Token]. - - Attributes: - type_ (google.cloud.documentai_v1beta2.types.Document.Page.Token.DetectedBreak.Type): - Detected break type. - """ - class Type(proto.Enum): - r"""Enum to denote the type of break found. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified break type. - SPACE (1): - A single whitespace. - WIDE_SPACE (2): - A wider whitespace. - HYPHEN (3): - A hyphen that indicates that a token has been - split across lines. - """ - TYPE_UNSPECIFIED = 0 - SPACE = 1 - WIDE_SPACE = 2 - HYPHEN = 3 - - type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Document.Page.Token.DetectedBreak.Type', - ) - - class StyleInfo(proto.Message): - r"""Font and other text style attributes. - - Attributes: - font_size (int): - Font size in points (``1`` point is ``¹⁄₇₂`` inches). - pixel_font_size (float): - Font size in pixels, equal to *unrounded - [font_size][google.cloud.documentai.v1beta2.Document.Page.Token.StyleInfo.font_size]* - - - *resolution* ÷ ``72.0``. - letter_spacing (float): - Letter spacing in points. - font_type (str): - Name or style of the font. - bold (bool): - Whether the text is bold (equivalent to - [font_weight][google.cloud.documentai.v1beta2.Document.Page.Token.StyleInfo.font_weight] - is at least ``700``). - italic (bool): - Whether the text is italic. - underlined (bool): - Whether the text is underlined. - strikeout (bool): - Whether the text is strikethrough. - subscript (bool): - Whether the text is a subscript. - superscript (bool): - Whether the text is a superscript. - smallcaps (bool): - Whether the text is in small caps. - font_weight (int): - TrueType weight on a scale ``100`` (thin) to ``1000`` - (ultra-heavy). Normal is ``400``, bold is ``700``. - handwritten (bool): - Whether the text is handwritten. - text_color (google.type.color_pb2.Color): - Color of the text. - background_color (google.type.color_pb2.Color): - Color of the background. - """ - - font_size: int = proto.Field( - proto.INT32, - number=1, - ) - pixel_font_size: float = proto.Field( - proto.DOUBLE, - number=2, - ) - letter_spacing: float = proto.Field( - proto.DOUBLE, - number=3, - ) - font_type: str = proto.Field( - proto.STRING, - number=4, - ) - bold: bool = proto.Field( - proto.BOOL, - number=5, - ) - italic: bool = proto.Field( - proto.BOOL, - number=6, - ) - underlined: bool = proto.Field( - proto.BOOL, - number=7, - ) - strikeout: bool = proto.Field( - proto.BOOL, - number=8, - ) - subscript: bool = proto.Field( - proto.BOOL, - number=9, - ) - superscript: bool = proto.Field( - proto.BOOL, - number=10, - ) - smallcaps: bool = proto.Field( - proto.BOOL, - number=11, - ) - font_weight: int = proto.Field( - proto.INT32, - number=12, - ) - handwritten: bool = proto.Field( - proto.BOOL, - number=13, - ) - text_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=14, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=15, - message=color_pb2.Color, - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Token.DetectedBreak', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=4, - message='Document.Provenance', - ) - style_info: 'Document.Page.Token.StyleInfo' = proto.Field( - proto.MESSAGE, - number=5, - message='Document.Page.Token.StyleInfo', - ) - - class Symbol(proto.Message): - r"""A detected symbol. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Symbol][google.cloud.documentai.v1beta2.Document.Page.Symbol]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class VisualElement(proto.Message): - r"""Detected non-text visual elements e.g. checkbox, signature - etc. on the page. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [VisualElement][google.cloud.documentai.v1beta2.Document.Page.VisualElement]. - type_ (str): - Type of the - [VisualElement][google.cloud.documentai.v1beta2.Document.Page.VisualElement]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - - class Table(proto.Message): - r"""A table representation similar to HTML table structure. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [Table][google.cloud.documentai.v1beta2.Document.Page.Table]. - header_rows (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): - Header rows of the table. - body_rows (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableRow]): - Body rows of the table. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta2.types.Document.Provenance): - The history of this table. - """ - - class TableRow(proto.Message): - r"""A row of table cells. - - Attributes: - cells (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.Table.TableCell]): - Cells that make up this row. - """ - - cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.Page.Table.TableCell', - ) - - class TableCell(proto.Message): - r"""A cell representation inside the table. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [TableCell][google.cloud.documentai.v1beta2.Document.Page.Table.TableCell]. - row_span (int): - How many rows this cell spans. - col_span (int): - How many columns this cell spans. - detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - row_span: int = proto.Field( - proto.INT32, - number=2, - ) - col_span: int = proto.Field( - proto.INT32, - number=3, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.Table.TableRow', - ) - body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.Table.TableRow', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=5, - message='Document.Provenance', - ) - - class FormField(proto.Message): - r"""A form field detected on the page. - - Attributes: - field_name (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta2.Document.Page.FormField] - name. e.g. ``Address``, ``Email``, ``Grand total``, - ``Phone number``, etc. - field_value (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta2.Document.Page.FormField] - value. - name_detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages for name - together with confidence. - value_detected_languages (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Page.DetectedLanguage]): - A list of detected languages for value - together with confidence. - value_type (str): - If the value is non-textual, this field represents the type. - Current valid values are: - - - blank (this indicates the ``field_value`` is normal text) - - ``unfilled_checkbox`` - - ``filled_checkbox`` - corrected_key_text (str): - 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_v1beta2.types.Document.Provenance): - The history of this annotation. - """ - - field_name: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - field_value: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Layout', - ) - name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - value_type: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_key_text: str = proto.Field( - proto.STRING, - number=6, - ) - corrected_value_text: str = proto.Field( - proto.STRING, - number=7, - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=8, - message='Document.Provenance', - ) - - class DetectedBarcode(proto.Message): - r"""A detected barcode. - - Attributes: - layout (google.cloud.documentai_v1beta2.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta2.Document.Page.Layout] - for - [DetectedBarcode][google.cloud.documentai.v1beta2.Document.Page.DetectedBarcode]. - barcode (google.cloud.documentai_v1beta2.types.Barcode): - Detailed barcode information of the - [DetectedBarcode][google.cloud.documentai.v1beta2.Document.Page.DetectedBarcode]. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - barcode: gcd_barcode.Barcode = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_barcode.Barcode, - ) - - class DetectedLanguage(proto.Message): - r"""Detected language for a structural component. - - Attributes: - language_code (str): - The `BCP-47 language - code `__, - such as ``en-US`` or ``sr-Latn``. - confidence (float): - Confidence of detected language. Range ``[0, 1]``. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - class ImageQualityScores(proto.Message): - r"""Image quality scores for the page image. - - Attributes: - quality_score (float): - The overall quality score. Range ``[0, 1]`` where ``1`` is - perfect quality. - detected_defects (MutableSequence[google.cloud.documentai_v1beta2.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 that the defect exists. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - quality_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - detected_defects: MutableSequence['Document.Page.ImageQualityScores.DetectedDefect'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.ImageQualityScores.DetectedDefect', - ) - - page_number: int = proto.Field( - proto.INT32, - number=1, - ) - image: 'Document.Page.Image' = proto.Field( - proto.MESSAGE, - number=13, - message='Document.Page.Image', - ) - transforms: MutableSequence['Document.Page.Matrix'] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='Document.Page.Matrix', - ) - dimension: 'Document.Page.Dimension' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Dimension', - ) - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Document.Page.Block', - ) - paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Document.Page.Paragraph', - ) - lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Document.Page.Line', - ) - tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='Document.Page.Token', - ) - visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Document.Page.VisualElement', - ) - tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Page.Table', - ) - form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='Document.Page.FormField', - ) - symbols: MutableSequence['Document.Page.Symbol'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='Document.Page.Symbol', - ) - detected_barcodes: MutableSequence['Document.Page.DetectedBarcode'] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message='Document.Page.DetectedBarcode', - ) - image_quality_scores: 'Document.Page.ImageQualityScores' = proto.Field( - proto.MESSAGE, - number=17, - message='Document.Page.ImageQualityScores', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=16, - message='Document.Provenance', - ) - - class Entity(proto.Message): - r"""An entity that could be a phrase in the text or a property - that belongs to the document. It is a known entity type, such as - a person, an organization, or location. - - Attributes: - text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): - Optional. 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): - 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_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. - normalized_value (google.cloud.documentai_v1beta2.types.Document.Entity.NormalizedValue): - Optional. Normalized entity value. Absent if - the extracted value could not be converted or - the type (e.g. address) is not supported for - certain parsers. This field is also only - populated for certain supported document types. - properties (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Entity]): - Optional. Entities can be nested to form a - hierarchical data structure representing the - content in the document. - provenance (google.cloud.documentai_v1beta2.types.Document.Provenance): - Optional. The history of this annotation. - redacted (bool): - Optional. Whether the entity will be redacted - for de-identification purposes. - """ - - class NormalizedValue(proto.Message): - r"""Parsed and normalized entity value. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - money_value (google.type.money_pb2.Money): - Money value. See also: - - https://github.com/googleapis/googleapis/blob/master/google/type/money.proto - - This field is a member of `oneof`_ ``structured_value``. - date_value (google.type.date_pb2.Date): - Date value. Includes year, month, day. See - also: - https://github.com/googleapis/googleapis/blob/master/google/type/date.proto - - This field is a member of `oneof`_ ``structured_value``. - datetime_value (google.type.datetime_pb2.DateTime): - DateTime value. Includes date, time, and - timezone. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/datetime.proto - - This field is a member of `oneof`_ ``structured_value``. - address_value (google.type.postal_address_pb2.PostalAddress): - Postal address. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/postal_address.proto - - This field is a member of `oneof`_ ``structured_value``. - boolean_value (bool): - Boolean value. Can be used for entities with - binary values, or for checkboxes. - - This field is a member of `oneof`_ ``structured_value``. - integer_value (int): - Integer value. - - This field is a member of `oneof`_ ``structured_value``. - float_value (float): - Float value. - - This field is a member of `oneof`_ ``structured_value``. - text (str): - Optional. An optional field to store a normalized string. - For some entity types, one of respective - ``structured_value`` fields may also be populated. Also not - all the types of ``structured_value`` will be normalized. - For example, some processors may not generate ``float`` or - ``integer`` normalized text by default. - - Below are sample formats mapped to structured values. - - - Money/Currency type (``money_value``) is in the ISO 4217 - text format. - - Date type (``date_value``) is in the ISO 8601 text - format. - - Datetime type (``datetime_value``) is in the ISO 8601 - text format. - """ - - money_value: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - oneof='structured_value', - message=money_pb2.Money, - ) - date_value: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - oneof='structured_value', - message=date_pb2.Date, - ) - datetime_value: datetime_pb2.DateTime = proto.Field( - proto.MESSAGE, - number=4, - oneof='structured_value', - message=datetime_pb2.DateTime, - ) - address_value: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=5, - oneof='structured_value', - message=postal_address_pb2.PostalAddress, - ) - boolean_value: bool = proto.Field( - proto.BOOL, - number=6, - oneof='structured_value', - ) - integer_value: int = proto.Field( - proto.INT32, - number=7, - oneof='structured_value', - ) - float_value: float = proto.Field( - proto.FLOAT, - number=8, - oneof='structured_value', - ) - text: str = proto.Field( - proto.STRING, - number=1, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - mention_text: str = proto.Field( - proto.STRING, - number=3, - ) - mention_id: str = proto.Field( - proto.STRING, - number=4, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - page_anchor: 'Document.PageAnchor' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.PageAnchor', - ) - id: str = proto.Field( - proto.STRING, - number=7, - ) - normalized_value: 'Document.Entity.NormalizedValue' = proto.Field( - proto.MESSAGE, - number=9, - message='Document.Entity.NormalizedValue', - ) - properties: MutableSequence['Document.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Entity', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=11, - message='Document.Provenance', - ) - redacted: bool = proto.Field( - proto.BOOL, - number=12, - ) - - class EntityRelation(proto.Message): - r"""Relationship between - [Entities][google.cloud.documentai.v1beta2.Document.Entity]. - - Attributes: - subject_id (str): - Subject entity id. - object_id (str): - Object entity id. - relation (str): - Relationship description. - """ - - subject_id: str = proto.Field( - proto.STRING, - number=1, - ) - object_id: str = proto.Field( - proto.STRING, - number=2, - ) - relation: str = proto.Field( - proto.STRING, - number=3, - ) - - class TextAnchor(proto.Message): - r"""Text reference indexing into the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - - Attributes: - text_segments (MutableSequence[google.cloud.documentai_v1beta2.types.Document.TextAnchor.TextSegment]): - The text segments from the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - content (str): - Contains the content of the text span so that users do not - have to look it up in the text_segments. It is always - populated for formFields. - """ - - class TextSegment(proto.Message): - r"""A text segment in the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. The - indices may be out of bounds which indicate that the text extends - into another document shard for large sharded documents. See - [ShardInfo.text_offset][google.cloud.documentai.v1beta2.Document.ShardInfo.text_offset] - - Attributes: - start_index (int): - [TextSegment][google.cloud.documentai.v1beta2.Document.TextAnchor.TextSegment] - start UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - end_index (int): - [TextSegment][google.cloud.documentai.v1beta2.Document.TextAnchor.TextSegment] - half open end UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - """ - - start_index: int = proto.Field( - proto.INT64, - number=1, - ) - end_index: int = proto.Field( - proto.INT64, - number=2, - ) - - text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.TextAnchor.TextSegment', - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class PageAnchor(proto.Message): - r"""Referencing the visual context of the entity in the - [Document.pages][google.cloud.documentai.v1beta2.Document.pages]. - Page anchors can be cross-page, consist of multiple bounding - polygons and optionally reference specific layout element types. - - Attributes: - page_refs (MutableSequence[google.cloud.documentai_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, 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_v1beta2.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.v1beta2.Document.PageAnchor.PageRef.bounding_poly] - instead. - bounding_poly (google.cloud.documentai_v1beta2.types.BoundingPoly): - Optional. Identifies the bounding polygon of a layout - element on the page. If ``layout_type`` is set, the bounding - polygon must be exactly the same to the layout element it's - referring to. - confidence (float): - Optional. Confidence of detected page element, if - applicable. Range ``[0, 1]``. - """ - class LayoutType(proto.Enum): - r"""The type of layout that is being referenced. - - Values: - LAYOUT_TYPE_UNSPECIFIED (0): - Layout Unspecified. - BLOCK (1): - References a - [Page.blocks][google.cloud.documentai.v1beta2.Document.Page.blocks] - element. - PARAGRAPH (2): - References a - [Page.paragraphs][google.cloud.documentai.v1beta2.Document.Page.paragraphs] - element. - LINE (3): - References a - [Page.lines][google.cloud.documentai.v1beta2.Document.Page.lines] - element. - TOKEN (4): - References a - [Page.tokens][google.cloud.documentai.v1beta2.Document.Page.tokens] - element. - VISUAL_ELEMENT (5): - References a - [Page.visual_elements][google.cloud.documentai.v1beta2.Document.Page.visual_elements] - element. - TABLE (6): - Refrrences a - [Page.tables][google.cloud.documentai.v1beta2.Document.Page.tables] - element. - FORM_FIELD (7): - References a - [Page.form_fields][google.cloud.documentai.v1beta2.Document.Page.form_fields] - element. - """ - LAYOUT_TYPE_UNSPECIFIED = 0 - BLOCK = 1 - PARAGRAPH = 2 - LINE = 3 - TOKEN = 4 - VISUAL_ELEMENT = 5 - TABLE = 6 - FORM_FIELD = 7 - - page: int = proto.Field( - proto.INT64, - number=1, - ) - layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( - proto.ENUM, - number=2, - enum='Document.PageAnchor.PageRef.LayoutType', - ) - layout_id: str = proto.Field( - proto.STRING, - number=3, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=4, - message=geometry.BoundingPoly, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - - page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.PageAnchor.PageRef', - ) - - class Provenance(proto.Message): - r"""Structure to identify provenance relationships between - annotations in different revisions. - - Attributes: - revision (int): - The index of the revision that produced this - element. - id (int): - The Id of this operation. Needs to be unique - within the scope of the revision. - parents (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Provenance.Parent]): - References to the original elements that are - replaced. - type_ (google.cloud.documentai_v1beta2.types.Document.Provenance.OperationType): - The type of provenance operation. - """ - class OperationType(proto.Enum): - r"""If a processor or agent does an explicit operation on - existing elements. - - Values: - OPERATION_TYPE_UNSPECIFIED (0): - Operation type unspecified. If no operation is specified a - provenance entry is simply used to match against a - ``parent``. - ADD (1): - Add an element. - REMOVE (2): - Remove an element identified by ``parent``. - UPDATE (7): - Updates any fields within the given - provenance scope of the message. It overwrites - the fields rather than replacing them. Use this - when you want to update a field value of an - entity without also updating all the child - properties. - REPLACE (3): - Currently unused. Replace an element identified by - ``parent``. - EVAL_REQUESTED (4): - Deprecated. Request human review for the element identified - by ``parent``. - EVAL_APPROVED (5): - Deprecated. Element is reviewed and approved - at human review, confidence will be set to 1.0. - EVAL_SKIPPED (6): - Deprecated. Element is skipped in the - validation process. - """ - OPERATION_TYPE_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - UPDATE = 7 - REPLACE = 3 - EVAL_REQUESTED = 4 - EVAL_APPROVED = 5 - EVAL_SKIPPED = 6 - - class Parent(proto.Message): - r"""The parent element the current element is based on. Used for - referencing/aligning, removal and replacement operations. - - Attributes: - revision (int): - The index of the index into current revision's parent_ids - list. - index (int): - The index of the parent item in the - corresponding item list (eg. list of entities, - properties within entities, etc.) in the parent - revision. - id (int): - The id of the parent provenance. - """ - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - index: int = proto.Field( - proto.INT32, - number=3, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - parents: MutableSequence['Document.Provenance.Parent'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance.Parent', - ) - type_: 'Document.Provenance.OperationType' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Provenance.OperationType', - ) - - class Revision(proto.Message): - r"""Contains past or forward revisions of this document. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - agent (str): - If the change was made by a person specify - the name or id of that person. - - This field is a member of `oneof`_ ``source``. - processor (str): - If the annotation was made by processor - identify the processor by its resource name. - - This field is a member of `oneof`_ ``source``. - id (str): - Id of the revision, internally generated by - doc proto storage. Unique within the context of - the document. - parent (MutableSequence[int]): - The revisions that this revision is based on. This can - include one or more parent (when documents are merged.) This - field represents the index into the ``revisions`` field. - parent_ids (MutableSequence[str]): - The revisions that this revision is based on. Must include - all the ids that have anything to do with this revision - - eg. there are ``provenance.parent.revision`` fields that - index into this field. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the revision was created, - internally generated by doc proto storage at the - time of create. - human_review (google.cloud.documentai_v1beta2.types.Document.Revision.HumanReview): - Human Review information of this revision. - """ - - class HumanReview(proto.Message): - r"""Human Review information of the document. - - Attributes: - state (str): - Human review state. e.g. ``requested``, ``succeeded``, - ``rejected``. - state_message (str): - A message providing more details about the current state of - processing. For example, the rejection reason when the state - is ``rejected``. - """ - - state: str = proto.Field( - proto.STRING, - number=1, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - - agent: str = proto.Field( - proto.STRING, - number=4, - oneof='source', - ) - processor: str = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - id: str = proto.Field( - proto.STRING, - number=1, - ) - parent: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=2, - ) - parent_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - human_review: 'Document.Revision.HumanReview' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.Revision.HumanReview', - ) - - class TextChange(proto.Message): - r"""This message is used for text changes aka. OCR corrections. - - Attributes: - text_anchor (google.cloud.documentai_v1beta2.types.Document.TextAnchor): - Provenance of the correction. Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta2.Document.text]. - There can only be a single ``TextAnchor.text_segments`` - element. If the start and end index of the text segment are - the same, the text change is inserted before that index. - changed_text (str): - The text that replaces the text identified in the - ``text_anchor``. - provenance (MutableSequence[google.cloud.documentai_v1beta2.types.Document.Provenance]): - The history of this annotation. - """ - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - changed_text: str = proto.Field( - proto.STRING, - number=2, - ) - provenance: MutableSequence['Document.Provenance'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - text: str = proto.Field( - proto.STRING, - number=4, - ) - text_styles: MutableSequence[Style] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Style, - ) - pages: MutableSequence[Page] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Page, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Entity, - ) - entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=EntityRelation, - ) - text_changes: MutableSequence[TextChange] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=TextChange, - ) - shard_info: ShardInfo = proto.Field( - proto.MESSAGE, - number=9, - message=ShardInfo, - ) - labels: MutableSequence[Label] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=Label, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - revisions: MutableSequence[Revision] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Revision, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py deleted file mode 100644 index ad4e66434619..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/document_understanding.py +++ /dev/null @@ -1,578 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1beta2.types import geometry -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta2', - manifest={ - 'BatchProcessDocumentsRequest', - 'ProcessDocumentRequest', - 'BatchProcessDocumentsResponse', - 'ProcessDocumentResponse', - 'OcrParams', - 'TableExtractionParams', - 'TableBoundHint', - 'FormExtractionParams', - 'KeyValuePairHint', - 'EntityExtractionParams', - 'AutoMlParams', - 'InputConfig', - 'OutputConfig', - 'GcsSource', - 'GcsDestination', - 'OperationMetadata', - }, -) - - -class BatchProcessDocumentsRequest(proto.Message): - r"""Request to batch process documents as an asynchronous operation. The - output is written to Cloud Storage as JSON in the [Document] format. - - Attributes: - requests (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]): - Required. Individual requests for each - document. - parent (str): - Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no location is specified, a region will be chosen - automatically. - """ - - requests: MutableSequence['ProcessDocumentRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ProcessDocumentRequest', - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ProcessDocumentRequest(proto.Message): - r"""Request to process one document. - - Attributes: - parent (str): - Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no location is specified, a region will be chosen - automatically. This field is only populated when used in - ProcessDocument method. - input_config (google.cloud.documentai_v1beta2.types.InputConfig): - Required. Information about the input file. - output_config (google.cloud.documentai_v1beta2.types.OutputConfig): - The desired output location. This field is - only needed in BatchProcessDocumentsRequest. - document_type (str): - Specifies a known document type for deeper - structure detection. Valid values are currently - "general" and "invoice". If not provided, - "general"\ is used as default. If any other - value is given, the request is rejected. - table_extraction_params (google.cloud.documentai_v1beta2.types.TableExtractionParams): - Controls table extraction behavior. If not - specified, the system will decide reasonable - defaults. - form_extraction_params (google.cloud.documentai_v1beta2.types.FormExtractionParams): - Controls form extraction behavior. If not - specified, the system will decide reasonable - defaults. - entity_extraction_params (google.cloud.documentai_v1beta2.types.EntityExtractionParams): - Controls entity extraction behavior. If not - specified, the system will decide reasonable - defaults. - ocr_params (google.cloud.documentai_v1beta2.types.OcrParams): - Controls OCR behavior. If not specified, the - system will decide reasonable defaults. - automl_params (google.cloud.documentai_v1beta2.types.AutoMlParams): - Controls AutoML model prediction behavior. - AutoMlParams cannot be used together with other - Params. - """ - - parent: str = proto.Field( - proto.STRING, - number=9, - ) - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='InputConfig', - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='OutputConfig', - ) - document_type: str = proto.Field( - proto.STRING, - number=3, - ) - table_extraction_params: 'TableExtractionParams' = proto.Field( - proto.MESSAGE, - number=4, - message='TableExtractionParams', - ) - form_extraction_params: 'FormExtractionParams' = proto.Field( - proto.MESSAGE, - number=5, - message='FormExtractionParams', - ) - entity_extraction_params: 'EntityExtractionParams' = proto.Field( - proto.MESSAGE, - number=6, - message='EntityExtractionParams', - ) - ocr_params: 'OcrParams' = proto.Field( - proto.MESSAGE, - number=7, - message='OcrParams', - ) - automl_params: 'AutoMlParams' = proto.Field( - proto.MESSAGE, - number=8, - message='AutoMlParams', - ) - - -class BatchProcessDocumentsResponse(proto.Message): - r"""Response to an batch document processing request. This is - returned in the LRO Operation after the operation is complete. - - Attributes: - responses (MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentResponse]): - Responses for each individual document. - """ - - responses: MutableSequence['ProcessDocumentResponse'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ProcessDocumentResponse', - ) - - -class ProcessDocumentResponse(proto.Message): - r"""Response to a single document processing request. - - Attributes: - input_config (google.cloud.documentai_v1beta2.types.InputConfig): - Information about the input file. This is the - same as the corresponding input config in the - request. - output_config (google.cloud.documentai_v1beta2.types.OutputConfig): - The output location of the parsed responses. The responses - are written to this location as JSON-serialized ``Document`` - objects. - """ - - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='InputConfig', - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='OutputConfig', - ) - - -class OcrParams(proto.Message): - r"""Parameters to control Optical Character Recognition (OCR) - behavior. - - Attributes: - language_hints (MutableSequence[str]): - List of languages to use for OCR. In most cases, an empty - value yields the best results since it enables automatic - language detection. For languages based on the Latin - alphabet, setting ``language_hints`` is not needed. In rare - cases, when the language of the text in the image is known, - setting a hint will help get better results (although it - will be a significant hindrance if the hint is wrong). - Document processing returns an error if one or more of the - specified languages is not one of the supported languages. - """ - - language_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class TableExtractionParams(proto.Message): - r"""Parameters to control table extraction behavior. - - Attributes: - enabled (bool): - Whether to enable table extraction. - table_bound_hints (MutableSequence[google.cloud.documentai_v1beta2.types.TableBoundHint]): - Optional. Table bounding box hints that can - be provided to complex cases which our algorithm - cannot locate the table(s) in. - header_hints (MutableSequence[str]): - Optional. Reserved for future use. - model_version (str): - Model version of the table extraction system. - Default is "builtin/stable". Specify - "builtin/latest" for the latest model. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - table_bound_hints: MutableSequence['TableBoundHint'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TableBoundHint', - ) - header_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - model_version: str = proto.Field( - proto.STRING, - number=4, - ) - - -class TableBoundHint(proto.Message): - r"""A hint for a table bounding box on the page for table - parsing. - - Attributes: - page_number (int): - Optional. Page number for multi-paged inputs - this hint applies to. If not provided, this hint - will apply to all pages by default. This value - is 1-based. - bounding_box (google.cloud.documentai_v1beta2.types.BoundingPoly): - Bounding box hint for a table on this page. The coordinates - must be normalized to [0,1] and the bounding box must be an - axis-aligned rectangle. - """ - - page_number: int = proto.Field( - proto.INT32, - number=1, - ) - bounding_box: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=2, - message=geometry.BoundingPoly, - ) - - -class FormExtractionParams(proto.Message): - r"""Parameters to control form extraction behavior. - - Attributes: - enabled (bool): - Whether to enable form extraction. - key_value_pair_hints (MutableSequence[google.cloud.documentai_v1beta2.types.KeyValuePairHint]): - Reserved for future use. - model_version (str): - Model version of the form extraction system. Default is - "builtin/stable". Specify "builtin/latest" for the latest - model. For custom form models, specify: - "custom/{model_name}". Model name format is - "bucket_name/path/to/modeldir" corresponding to - "gs://bucket_name/path/to/modeldir" where annotated examples - are stored. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - key_value_pair_hints: MutableSequence['KeyValuePairHint'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='KeyValuePairHint', - ) - model_version: str = proto.Field( - proto.STRING, - number=3, - ) - - -class KeyValuePairHint(proto.Message): - r"""Reserved for future use. - - Attributes: - key (str): - The key text for the hint. - value_types (MutableSequence[str]): - Type of the value. This is case-insensitive, and could be - one of: ADDRESS, LOCATION, ORGANIZATION, PERSON, - PHONE_NUMBER, ID, NUMBER, EMAIL, PRICE, TERMS, DATE, NAME. - Types not in this list will be ignored. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - value_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class EntityExtractionParams(proto.Message): - r"""Parameters to control entity extraction behavior. - - Attributes: - enabled (bool): - Whether to enable entity extraction. - model_version (str): - Model version of the entity extraction. - Default is "builtin/stable". Specify - "builtin/latest" for the latest model. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - model_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AutoMlParams(proto.Message): - r"""Parameters to control AutoML model prediction behavior. - - Attributes: - model (str): - Resource name of the AutoML model. - - Format: - ``projects/{project-id}/locations/{location-id}/models/{model-id}``. - """ - - model: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InputConfig(proto.Message): - r"""The desired input location and metadata. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_source (google.cloud.documentai_v1beta2.types.GcsSource): - The Google Cloud Storage location to read the - input from. This must be a single file. - - This field is a member of `oneof`_ ``source``. - contents (bytes): - Content in bytes, represented as a stream of bytes. Note: As - with all ``bytes`` fields, proto buffer messages use a pure - binary representation, whereas JSON representations use - base64. - - This field only works for synchronous ProcessDocument - method. - - This field is a member of `oneof`_ ``source``. - mime_type (str): - Required. Mimetype of the input. Current supported mimetypes - are application/pdf, image/tiff, and image/gif. In addition, - application/json type is supported for requests with - [ProcessDocumentRequest.automl_params][google.cloud.documentai.v1beta2.ProcessDocumentRequest.automl_params] - field set. The JSON file needs to be in - [Document][google.cloud.documentai.v1beta2.Document] format. - """ - - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsSource', - ) - contents: bytes = proto.Field( - proto.BYTES, - number=3, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class OutputConfig(proto.Message): - r"""The desired output location and metadata. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.cloud.documentai_v1beta2.types.GcsDestination): - The Google Cloud Storage location to write - the output to. - - This field is a member of `oneof`_ ``destination``. - pages_per_shard (int): - The max number of pages to include into each output Document - shard JSON on Google Cloud Storage. - - The valid range is [1, 100]. If not specified, the default - value is 20. - - For example, for one pdf file with 100 pages, 100 parsed - pages will be produced. If ``pages_per_shard`` = 20, then 5 - Document shard JSON files each containing 20 parsed pages - will be written under the prefix - [OutputConfig.gcs_destination.uri][] and suffix - pages-x-to-y.json where x and y are 1-indexed page numbers. - - Example GCS outputs with 157 pages and pages_per_shard = 50: - - pages-001-to-050.json pages-051-to-100.json - pages-101-to-150.json pages-151-to-157.json - """ - - gcs_destination: 'GcsDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - pages_per_shard: int = proto.Field( - proto.INT32, - number=2, - ) - - -class GcsSource(proto.Message): - r"""The Google Cloud Storage location where the input file will - be read from. - - Attributes: - uri (str): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GcsDestination(proto.Message): - r"""The Google Cloud Storage location where the output file will - be written to. - - Attributes: - uri (str): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OperationMetadata(proto.Message): - r"""Contains metadata for the BatchProcessDocuments operation. - - Attributes: - state (google.cloud.documentai_v1beta2.types.OperationMetadata.State): - The state of the current batch processing. - state_message (str): - A message providing more details about the - current state of processing. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - """ - class State(proto.Enum): - r""" - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - ACCEPTED (1): - Request is received. - WAITING (2): - Request operation is waiting for scheduling. - RUNNING (3): - Request is being processed. - SUCCEEDED (4): - The batch processing completed successfully. - CANCELLED (5): - The batch processing was cancelled. - FAILED (6): - The batch processing has failed. - """ - STATE_UNSPECIFIED = 0 - ACCEPTED = 1 - WAITING = 2 - RUNNING = 3 - SUCCEEDED = 4 - CANCELLED = 5 - FAILED = 6 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py b/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py deleted file mode 100644 index f99cd7341634..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/google/cloud/documentai_v1beta2/types/geometry.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta2', - manifest={ - 'Vertex', - 'NormalizedVertex', - 'BoundingPoly', - }, -) - - -class Vertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the vertex coordinates are in the same scale as the - original image. - - Attributes: - x (int): - X coordinate. - y (int): - Y coordinate (starts from the top of the - image). - """ - - x: int = proto.Field( - proto.INT32, - number=1, - ) - y: int = proto.Field( - proto.INT32, - number=2, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate (starts from the top of the - image). - """ - - x: float = proto.Field( - proto.FLOAT, - number=1, - ) - y: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class BoundingPoly(proto.Message): - r"""A bounding polygon for the detected image annotation. - - Attributes: - vertices (MutableSequence[google.cloud.documentai_v1beta2.types.Vertex]): - The bounding polygon vertices. - normalized_vertices (MutableSequence[google.cloud.documentai_v1beta2.types.NormalizedVertex]): - The bounding polygon normalized vertices. - """ - - vertices: MutableSequence['Vertex'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/mypy.ini b/owl-bot-staging/google-cloud-documentai/v1beta2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/noxfile.py b/owl-bot-staging/google-cloud-documentai/v1beta2/noxfile.py deleted file mode 100644 index 6d793e3b9ead..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/noxfile.py +++ /dev/null @@ -1,253 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-documentai' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@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=ALL_PYTHON[-1]) -def prerelease_deps(session): - """Run the unit test suite against pre-release versions of dependencies.""" - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/documentai_v1beta2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - '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==7.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, - ) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py b/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py deleted file mode 100644 index 460ca2fce376..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py deleted file mode 100644 index b381b928b678..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py b/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py deleted file mode 100644 index 54eef08269df..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py deleted file mode 100644 index f81a39312de1..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/documentai_v1beta2_generated_document_understanding_service_process_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json b/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json deleted file mode 100644 index ef56bd7e3eb3..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json +++ /dev/null @@ -1,329 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.documentai.v1beta2", - "version": "v1beta2" - } - ], - "language": "PYTHON", - "name": "google-cloud-documentai", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient", - "shortName": "DocumentUnderstandingServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient", - "shortName": "DocumentUnderstandingServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.BatchProcessDocumentsRequest" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.documentai_v1beta2.types.ProcessDocumentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_BatchProcessDocuments_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_batch_process_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient", - "shortName": "DocumentUnderstandingServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceAsyncClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.ProcessDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta2.types.Document", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta2_generated_document_understanding_service_process_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_process_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient", - "shortName": "DocumentUnderstandingServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta2.DocumentUnderstandingServiceClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta2.DocumentUnderstandingService", - "shortName": "DocumentUnderstandingService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta2.types.ProcessDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta2.types.Document", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta2_generated_document_understanding_service_process_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta2_generated_DocumentUnderstandingService_ProcessDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta2_generated_document_understanding_service_process_document_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py b/owl-bot-staging/google-cloud-documentai/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py deleted file mode 100644 index f49c705fd83e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/scripts/fixup_documentai_v1beta2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/setup.py b/owl-bot-staging/google-cloud-documentai/v1beta2/setup.py deleted file mode 100644 index 11e72a1d001b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/setup.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re - -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 = None - -with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <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/google-cloud-python/tree/main/packages/google-cloud-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.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.7.txt deleted file mode 100644 index b8a550c73855..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta2/tests/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/tests/unit/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/gapic/documentai_v1beta2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py b/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py deleted file mode 100644 index 43626a405c34..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta2/tests/unit/gapic/documentai_v1beta2/test_document_understanding_service.py +++ /dev/null @@ -1,2437 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 google.api_core import api_core_version -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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 - -def test__read_environment_variables(): - assert DocumentUnderstandingServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DocumentUnderstandingServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DocumentUnderstandingServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DocumentUnderstandingServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert DocumentUnderstandingServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DocumentUnderstandingServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DocumentUnderstandingServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentUnderstandingServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert DocumentUnderstandingServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert DocumentUnderstandingServiceClient._get_client_cert_source(None, False) is None - assert DocumentUnderstandingServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DocumentUnderstandingServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - 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_default_cert_source): - assert DocumentUnderstandingServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DocumentUnderstandingServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DocumentUnderstandingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentUnderstandingServiceClient)) -@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentUnderstandingServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DocumentUnderstandingServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentUnderstandingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentUnderstandingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DocumentUnderstandingServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DocumentUnderstandingServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DocumentUnderstandingServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentUnderstandingServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DocumentUnderstandingServiceClient._get_api_endpoint(None, None, default_universe, "always") == DocumentUnderstandingServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentUnderstandingServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DocumentUnderstandingServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentUnderstandingServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DocumentUnderstandingServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentUnderstandingServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert DocumentUnderstandingServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DocumentUnderstandingServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DocumentUnderstandingServiceClient._get_universe_domain(None, None) == DocumentUnderstandingServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DocumentUnderstandingServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentUnderstandingServiceClient, transports.DocumentUnderstandingServiceGrpcTransport, "grpc"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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_TEMPLATE", modify_default_endpoint_template(DocumentUnderstandingServiceClient)) -@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE", modify_default_endpoint_template(DocumentUnderstandingServiceClient)) -@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - DocumentUnderstandingServiceClient, DocumentUnderstandingServiceAsyncClient -]) -@mock.patch.object(DocumentUnderstandingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentUnderstandingServiceClient)) -@mock.patch.object(DocumentUnderstandingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentUnderstandingServiceAsyncClient)) -def test_document_understanding_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DocumentUnderstandingServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentUnderstandingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentUnderstandingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 = client_options.ClientOptions() - 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', - '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_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_cancel_operation(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 = 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_asyncio"): - 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 = 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 = 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 = 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 = 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 = 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 = DocumentUnderstandingServiceClient( - 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 = DocumentUnderstandingServiceAsyncClient( - 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 = 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 = 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_asyncio"): - 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 = 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 = 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 = 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 = 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 = 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 = DocumentUnderstandingServiceClient( - 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 = DocumentUnderstandingServiceAsyncClient( - 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 = 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 = 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_asyncio"): - 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 = 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 = 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 = 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 = 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 = 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 = DocumentUnderstandingServiceClient( - 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 = DocumentUnderstandingServiceAsyncClient( - 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 = 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 = 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_asyncio"): - 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 = 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 = 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 = 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 = 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 = 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 = DocumentUnderstandingServiceClient( - 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 = DocumentUnderstandingServiceAsyncClient( - 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = DocumentUnderstandingServiceClient( - 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 = DocumentUnderstandingServiceAsyncClient( - 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 = 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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/google-cloud-documentai/v1beta3/.coveragerc b/owl-bot-staging/google-cloud-documentai/v1beta3/.coveragerc deleted file mode 100644 index 46ab6093e34b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/documentai/__init__.py - google/cloud/documentai/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/.flake8 b/owl-bot-staging/google-cloud-documentai/v1beta3/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/MANIFEST.in b/owl-bot-staging/google-cloud-documentai/v1beta3/MANIFEST.in deleted file mode 100644 index af799d71f5e1..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/documentai *.py -recursive-include google/cloud/documentai_v1beta3 *.py diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/README.rst b/owl-bot-staging/google-cloud-documentai/v1beta3/README.rst deleted file mode 100644 index 484a3c1c8fa7..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Documentai API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Documentai API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/_static/custom.css b/owl-bot-staging/google-cloud-documentai/v1beta3/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/conf.py b/owl-bot-staging/google-cloud-documentai/v1beta3/docs/conf.py deleted file mode 100644 index 8d93c59cdbb8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2023, 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 = 'en' - -# 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/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/document_processor_service.rst b/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/document_processor_service.rst deleted file mode 100644 index 4d8d5f9ef5cc..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/document_processor_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentProcessorService ------------------------------------------- - -.. automodule:: google.cloud.documentai_v1beta3.services.document_processor_service - :members: - :inherited-members: - -.. automodule:: google.cloud.documentai_v1beta3.services.document_processor_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/document_service.rst b/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/document_service.rst deleted file mode 100644 index 4ac25775f8b6..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/document_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentService ---------------------------------- - -.. automodule:: google.cloud.documentai_v1beta3.services.document_service - :members: - :inherited-members: - -.. automodule:: google.cloud.documentai_v1beta3.services.document_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/services_.rst b/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/services_.rst deleted file mode 100644 index 7389a2275fa8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Documentai v1beta3 API -================================================ -.. toctree:: - :maxdepth: 2 - - document_processor_service - document_service diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/types_.rst b/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/types_.rst deleted file mode 100644 index 31b489da1ca7..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/documentai_v1beta3/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Documentai v1beta3 API -============================================= - -.. automodule:: google.cloud.documentai_v1beta3.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/index.rst b/owl-bot-staging/google-cloud-documentai/v1beta3/docs/index.rst deleted file mode 100644 index f4d3a84d9471..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - documentai_v1beta3/services - documentai_v1beta3/types diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/__init__.py deleted file mode 100644 index 8747e3c592b6..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/__init__.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.services.document_service.client import DocumentServiceClient -from google.cloud.documentai_v1beta3.services.document_service.async_client import DocumentServiceAsyncClient - -from google.cloud.documentai_v1beta3.types.barcode import Barcode -from google.cloud.documentai_v1beta3.types.dataset import BatchDatasetDocuments -from google.cloud.documentai_v1beta3.types.dataset import Dataset -from google.cloud.documentai_v1beta3.types.dataset import DatasetSchema -from google.cloud.documentai_v1beta3.types.dataset import DocumentId -from google.cloud.documentai_v1beta3.types.document import Document -from google.cloud.documentai_v1beta3.types.document import RevisionRef -from google.cloud.documentai_v1beta3.types.document_io import BatchDocumentsInputConfig -from google.cloud.documentai_v1beta3.types.document_io import DocumentOutputConfig -from google.cloud.documentai_v1beta3.types.document_io import GcsDocument -from google.cloud.documentai_v1beta3.types.document_io import GcsDocuments -from google.cloud.documentai_v1beta3.types.document_io import GcsPrefix -from google.cloud.documentai_v1beta3.types.document_io import OcrConfig -from google.cloud.documentai_v1beta3.types.document_io import RawDocument -from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import BatchProcessResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import CreateProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DeleteProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DeployProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import DisableProcessorResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import EnableProcessorResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import EvaluateProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import FetchProcessorTypesRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import FetchProcessorTypesResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import GetEvaluationRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorTypeRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import GetProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import HumanReviewStatus -from google.cloud.documentai_v1beta3.types.document_processor_service import ImportProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import ImportProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ImportProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ListEvaluationsRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListEvaluationsResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorsRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorsResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorTypesRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorTypesResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorVersionsRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ListProcessorVersionsResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessOptions -from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ProcessResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentOperationMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import ReviewDocumentResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import SetDefaultProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import TrainProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionMetadata -from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionRequest -from google.cloud.documentai_v1beta3.types.document_processor_service import UndeployProcessorVersionResponse -from google.cloud.documentai_v1beta3.types.document_schema import DocumentSchema -from google.cloud.documentai_v1beta3.types.document_schema import EntityTypeMetadata -from google.cloud.documentai_v1beta3.types.document_schema import FieldExtractionMetadata -from google.cloud.documentai_v1beta3.types.document_schema import PropertyMetadata -from google.cloud.documentai_v1beta3.types.document_schema import SummaryOptions -from google.cloud.documentai_v1beta3.types.document_service import BatchDeleteDocumentsMetadata -from google.cloud.documentai_v1beta3.types.document_service import BatchDeleteDocumentsRequest -from google.cloud.documentai_v1beta3.types.document_service import BatchDeleteDocumentsResponse -from google.cloud.documentai_v1beta3.types.document_service import DocumentMetadata -from google.cloud.documentai_v1beta3.types.document_service import DocumentPageRange -from google.cloud.documentai_v1beta3.types.document_service import GetDatasetSchemaRequest -from google.cloud.documentai_v1beta3.types.document_service import GetDocumentRequest -from google.cloud.documentai_v1beta3.types.document_service import GetDocumentResponse -from google.cloud.documentai_v1beta3.types.document_service import ImportDocumentsMetadata -from google.cloud.documentai_v1beta3.types.document_service import ImportDocumentsRequest -from google.cloud.documentai_v1beta3.types.document_service import ImportDocumentsResponse -from google.cloud.documentai_v1beta3.types.document_service import ListDocumentsRequest -from google.cloud.documentai_v1beta3.types.document_service import ListDocumentsResponse -from google.cloud.documentai_v1beta3.types.document_service import UpdateDatasetOperationMetadata -from google.cloud.documentai_v1beta3.types.document_service import UpdateDatasetRequest -from google.cloud.documentai_v1beta3.types.document_service import UpdateDatasetSchemaRequest -from google.cloud.documentai_v1beta3.types.document_service import DatasetSplitType -from google.cloud.documentai_v1beta3.types.document_service import DocumentLabelingState -from google.cloud.documentai_v1beta3.types.evaluation import Evaluation -from google.cloud.documentai_v1beta3.types.evaluation import EvaluationReference -from google.cloud.documentai_v1beta3.types.geometry import BoundingPoly -from google.cloud.documentai_v1beta3.types.geometry import NormalizedVertex -from google.cloud.documentai_v1beta3.types.geometry import Vertex -from google.cloud.documentai_v1beta3.types.operation_metadata import CommonOperationMetadata -from google.cloud.documentai_v1beta3.types.processor import Processor -from google.cloud.documentai_v1beta3.types.processor import ProcessorVersion -from google.cloud.documentai_v1beta3.types.processor import ProcessorVersionAlias -from google.cloud.documentai_v1beta3.types.processor_type import ProcessorType - -__all__ = ('DocumentProcessorServiceClient', - 'DocumentProcessorServiceAsyncClient', - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', - 'Barcode', - 'BatchDatasetDocuments', - 'Dataset', - 'DatasetSchema', - 'DocumentId', - 'Document', - 'RevisionRef', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'OcrConfig', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ImportProcessorVersionMetadata', - 'ImportProcessorVersionRequest', - 'ImportProcessorVersionResponse', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessOptions', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'EntityTypeMetadata', - 'FieldExtractionMetadata', - 'PropertyMetadata', - 'SummaryOptions', - 'BatchDeleteDocumentsMetadata', - 'BatchDeleteDocumentsRequest', - 'BatchDeleteDocumentsResponse', - 'DocumentMetadata', - 'DocumentPageRange', - 'GetDatasetSchemaRequest', - 'GetDocumentRequest', - 'GetDocumentResponse', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDatasetOperationMetadata', - 'UpdateDatasetRequest', - 'UpdateDatasetSchemaRequest', - 'DatasetSplitType', - 'DocumentLabelingState', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorVersionAlias', - 'ProcessorType', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/gapic_version.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/py.typed b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/py.typed deleted file mode 100644 index 81b450017987..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/__init__.py deleted file mode 100644 index 5267fe027909..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/__init__.py +++ /dev/null @@ -1,232 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.document_processor_service import DocumentProcessorServiceClient -from .services.document_processor_service import DocumentProcessorServiceAsyncClient -from .services.document_service import DocumentServiceClient -from .services.document_service import DocumentServiceAsyncClient - -from .types.barcode import Barcode -from .types.dataset import BatchDatasetDocuments -from .types.dataset import Dataset -from .types.dataset import DatasetSchema -from .types.dataset import DocumentId -from .types.document import Document -from .types.document import RevisionRef -from .types.document_io import BatchDocumentsInputConfig -from .types.document_io import DocumentOutputConfig -from .types.document_io import GcsDocument -from .types.document_io import GcsDocuments -from .types.document_io import GcsPrefix -from .types.document_io import OcrConfig -from .types.document_io import RawDocument -from .types.document_processor_service import BatchProcessMetadata -from .types.document_processor_service import BatchProcessRequest -from .types.document_processor_service import BatchProcessResponse -from .types.document_processor_service import CreateProcessorRequest -from .types.document_processor_service import DeleteProcessorMetadata -from .types.document_processor_service import DeleteProcessorRequest -from .types.document_processor_service import DeleteProcessorVersionMetadata -from .types.document_processor_service import DeleteProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionMetadata -from .types.document_processor_service import DeployProcessorVersionRequest -from .types.document_processor_service import DeployProcessorVersionResponse -from .types.document_processor_service import DisableProcessorMetadata -from .types.document_processor_service import DisableProcessorRequest -from .types.document_processor_service import DisableProcessorResponse -from .types.document_processor_service import EnableProcessorMetadata -from .types.document_processor_service import EnableProcessorRequest -from .types.document_processor_service import EnableProcessorResponse -from .types.document_processor_service import EvaluateProcessorVersionMetadata -from .types.document_processor_service import EvaluateProcessorVersionRequest -from .types.document_processor_service import EvaluateProcessorVersionResponse -from .types.document_processor_service import FetchProcessorTypesRequest -from .types.document_processor_service import FetchProcessorTypesResponse -from .types.document_processor_service import GetEvaluationRequest -from .types.document_processor_service import GetProcessorRequest -from .types.document_processor_service import GetProcessorTypeRequest -from .types.document_processor_service import GetProcessorVersionRequest -from .types.document_processor_service import HumanReviewStatus -from .types.document_processor_service import ImportProcessorVersionMetadata -from .types.document_processor_service import ImportProcessorVersionRequest -from .types.document_processor_service import ImportProcessorVersionResponse -from .types.document_processor_service import ListEvaluationsRequest -from .types.document_processor_service import ListEvaluationsResponse -from .types.document_processor_service import ListProcessorsRequest -from .types.document_processor_service import ListProcessorsResponse -from .types.document_processor_service import ListProcessorTypesRequest -from .types.document_processor_service import ListProcessorTypesResponse -from .types.document_processor_service import ListProcessorVersionsRequest -from .types.document_processor_service import ListProcessorVersionsResponse -from .types.document_processor_service import ProcessOptions -from .types.document_processor_service import ProcessRequest -from .types.document_processor_service import ProcessResponse -from .types.document_processor_service import ReviewDocumentOperationMetadata -from .types.document_processor_service import ReviewDocumentRequest -from .types.document_processor_service import ReviewDocumentResponse -from .types.document_processor_service import SetDefaultProcessorVersionMetadata -from .types.document_processor_service import SetDefaultProcessorVersionRequest -from .types.document_processor_service import SetDefaultProcessorVersionResponse -from .types.document_processor_service import TrainProcessorVersionMetadata -from .types.document_processor_service import TrainProcessorVersionRequest -from .types.document_processor_service import TrainProcessorVersionResponse -from .types.document_processor_service import UndeployProcessorVersionMetadata -from .types.document_processor_service import UndeployProcessorVersionRequest -from .types.document_processor_service import UndeployProcessorVersionResponse -from .types.document_schema import DocumentSchema -from .types.document_schema import EntityTypeMetadata -from .types.document_schema import FieldExtractionMetadata -from .types.document_schema import PropertyMetadata -from .types.document_schema import SummaryOptions -from .types.document_service import BatchDeleteDocumentsMetadata -from .types.document_service import BatchDeleteDocumentsRequest -from .types.document_service import BatchDeleteDocumentsResponse -from .types.document_service import DocumentMetadata -from .types.document_service import DocumentPageRange -from .types.document_service import GetDatasetSchemaRequest -from .types.document_service import GetDocumentRequest -from .types.document_service import GetDocumentResponse -from .types.document_service import ImportDocumentsMetadata -from .types.document_service import ImportDocumentsRequest -from .types.document_service import ImportDocumentsResponse -from .types.document_service import ListDocumentsRequest -from .types.document_service import ListDocumentsResponse -from .types.document_service import UpdateDatasetOperationMetadata -from .types.document_service import UpdateDatasetRequest -from .types.document_service import UpdateDatasetSchemaRequest -from .types.document_service import DatasetSplitType -from .types.document_service import DocumentLabelingState -from .types.evaluation import Evaluation -from .types.evaluation import EvaluationReference -from .types.geometry import BoundingPoly -from .types.geometry import NormalizedVertex -from .types.geometry import Vertex -from .types.operation_metadata import CommonOperationMetadata -from .types.processor import Processor -from .types.processor import ProcessorVersion -from .types.processor import ProcessorVersionAlias -from .types.processor_type import ProcessorType - -__all__ = ( - 'DocumentProcessorServiceAsyncClient', - 'DocumentServiceAsyncClient', -'Barcode', -'BatchDatasetDocuments', -'BatchDeleteDocumentsMetadata', -'BatchDeleteDocumentsRequest', -'BatchDeleteDocumentsResponse', -'BatchDocumentsInputConfig', -'BatchProcessMetadata', -'BatchProcessRequest', -'BatchProcessResponse', -'BoundingPoly', -'CommonOperationMetadata', -'CreateProcessorRequest', -'Dataset', -'DatasetSchema', -'DatasetSplitType', -'DeleteProcessorMetadata', -'DeleteProcessorRequest', -'DeleteProcessorVersionMetadata', -'DeleteProcessorVersionRequest', -'DeployProcessorVersionMetadata', -'DeployProcessorVersionRequest', -'DeployProcessorVersionResponse', -'DisableProcessorMetadata', -'DisableProcessorRequest', -'DisableProcessorResponse', -'Document', -'DocumentId', -'DocumentLabelingState', -'DocumentMetadata', -'DocumentOutputConfig', -'DocumentPageRange', -'DocumentProcessorServiceClient', -'DocumentSchema', -'DocumentServiceClient', -'EnableProcessorMetadata', -'EnableProcessorRequest', -'EnableProcessorResponse', -'EntityTypeMetadata', -'EvaluateProcessorVersionMetadata', -'EvaluateProcessorVersionRequest', -'EvaluateProcessorVersionResponse', -'Evaluation', -'EvaluationReference', -'FetchProcessorTypesRequest', -'FetchProcessorTypesResponse', -'FieldExtractionMetadata', -'GcsDocument', -'GcsDocuments', -'GcsPrefix', -'GetDatasetSchemaRequest', -'GetDocumentRequest', -'GetDocumentResponse', -'GetEvaluationRequest', -'GetProcessorRequest', -'GetProcessorTypeRequest', -'GetProcessorVersionRequest', -'HumanReviewStatus', -'ImportDocumentsMetadata', -'ImportDocumentsRequest', -'ImportDocumentsResponse', -'ImportProcessorVersionMetadata', -'ImportProcessorVersionRequest', -'ImportProcessorVersionResponse', -'ListDocumentsRequest', -'ListDocumentsResponse', -'ListEvaluationsRequest', -'ListEvaluationsResponse', -'ListProcessorTypesRequest', -'ListProcessorTypesResponse', -'ListProcessorVersionsRequest', -'ListProcessorVersionsResponse', -'ListProcessorsRequest', -'ListProcessorsResponse', -'NormalizedVertex', -'OcrConfig', -'ProcessOptions', -'ProcessRequest', -'ProcessResponse', -'Processor', -'ProcessorType', -'ProcessorVersion', -'ProcessorVersionAlias', -'PropertyMetadata', -'RawDocument', -'ReviewDocumentOperationMetadata', -'ReviewDocumentRequest', -'ReviewDocumentResponse', -'RevisionRef', -'SetDefaultProcessorVersionMetadata', -'SetDefaultProcessorVersionRequest', -'SetDefaultProcessorVersionResponse', -'SummaryOptions', -'TrainProcessorVersionMetadata', -'TrainProcessorVersionRequest', -'TrainProcessorVersionResponse', -'UndeployProcessorVersionMetadata', -'UndeployProcessorVersionRequest', -'UndeployProcessorVersionResponse', -'UpdateDatasetOperationMetadata', -'UpdateDatasetRequest', -'UpdateDatasetSchemaRequest', -'Vertex', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json deleted file mode 100644 index 9d32da0a443b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/gapic_metadata.json +++ /dev/null @@ -1,497 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.documentai_v1beta3", - "protoPackage": "google.cloud.documentai.v1beta3", - "schema": "1.0", - "services": { - "DocumentProcessorService": { - "clients": { - "grpc": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ImportProcessorVersion": { - "methods": [ - "import_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentProcessorServiceAsyncClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ImportProcessorVersion": { - "methods": [ - "import_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentProcessorServiceClient", - "rpcs": { - "BatchProcessDocuments": { - "methods": [ - "batch_process_documents" - ] - }, - "CreateProcessor": { - "methods": [ - "create_processor" - ] - }, - "DeleteProcessor": { - "methods": [ - "delete_processor" - ] - }, - "DeleteProcessorVersion": { - "methods": [ - "delete_processor_version" - ] - }, - "DeployProcessorVersion": { - "methods": [ - "deploy_processor_version" - ] - }, - "DisableProcessor": { - "methods": [ - "disable_processor" - ] - }, - "EnableProcessor": { - "methods": [ - "enable_processor" - ] - }, - "EvaluateProcessorVersion": { - "methods": [ - "evaluate_processor_version" - ] - }, - "FetchProcessorTypes": { - "methods": [ - "fetch_processor_types" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetProcessor": { - "methods": [ - "get_processor" - ] - }, - "GetProcessorType": { - "methods": [ - "get_processor_type" - ] - }, - "GetProcessorVersion": { - "methods": [ - "get_processor_version" - ] - }, - "ImportProcessorVersion": { - "methods": [ - "import_processor_version" - ] - }, - "ListEvaluations": { - "methods": [ - "list_evaluations" - ] - }, - "ListProcessorTypes": { - "methods": [ - "list_processor_types" - ] - }, - "ListProcessorVersions": { - "methods": [ - "list_processor_versions" - ] - }, - "ListProcessors": { - "methods": [ - "list_processors" - ] - }, - "ProcessDocument": { - "methods": [ - "process_document" - ] - }, - "ReviewDocument": { - "methods": [ - "review_document" - ] - }, - "SetDefaultProcessorVersion": { - "methods": [ - "set_default_processor_version" - ] - }, - "TrainProcessorVersion": { - "methods": [ - "train_processor_version" - ] - }, - "UndeployProcessorVersion": { - "methods": [ - "undeploy_processor_version" - ] - } - } - } - } - }, - "DocumentService": { - "clients": { - "grpc": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "BatchDeleteDocuments": { - "methods": [ - "batch_delete_documents" - ] - }, - "GetDatasetSchema": { - "methods": [ - "get_dataset_schema" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "UpdateDataset": { - "methods": [ - "update_dataset" - ] - }, - "UpdateDatasetSchema": { - "methods": [ - "update_dataset_schema" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentServiceAsyncClient", - "rpcs": { - "BatchDeleteDocuments": { - "methods": [ - "batch_delete_documents" - ] - }, - "GetDatasetSchema": { - "methods": [ - "get_dataset_schema" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "UpdateDataset": { - "methods": [ - "update_dataset" - ] - }, - "UpdateDatasetSchema": { - "methods": [ - "update_dataset_schema" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "BatchDeleteDocuments": { - "methods": [ - "batch_delete_documents" - ] - }, - "GetDatasetSchema": { - "methods": [ - "get_dataset_schema" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "UpdateDataset": { - "methods": [ - "update_dataset" - ] - }, - "UpdateDatasetSchema": { - "methods": [ - "update_dataset_schema" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/py.typed b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/py.typed deleted file mode 100644 index 81b450017987..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-documentai package uses inline types. diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py deleted file mode 100644 index 326eb2c14112..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py deleted file mode 100644 index bd9e621b0661..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py +++ /dev/null @@ -1,3266 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -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 Document AI 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 - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DocumentProcessorServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - - evaluation_path = staticmethod(DocumentProcessorServiceClient.evaluation_path) - parse_evaluation_path = staticmethod(DocumentProcessorServiceClient.parse_evaluation_path) - human_review_config_path = staticmethod(DocumentProcessorServiceClient.human_review_config_path) - parse_human_review_config_path = staticmethod(DocumentProcessorServiceClient.parse_human_review_config_path) - processor_path = staticmethod(DocumentProcessorServiceClient.processor_path) - parse_processor_path = staticmethod(DocumentProcessorServiceClient.parse_processor_path) - processor_type_path = staticmethod(DocumentProcessorServiceClient.processor_type_path) - parse_processor_type_path = staticmethod(DocumentProcessorServiceClient.parse_processor_type_path) - processor_version_path = staticmethod(DocumentProcessorServiceClient.processor_version_path) - parse_processor_version_path = staticmethod(DocumentProcessorServiceClient.parse_processor_version_path) - common_billing_account_path = staticmethod(DocumentProcessorServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentProcessorServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentProcessorServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentProcessorServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentProcessorServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentProcessorServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentProcessorServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentProcessorServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentProcessorServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentProcessorServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_info.__func__(DocumentProcessorServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceAsyncClient: The constructed client. - """ - return DocumentProcessorServiceClient.from_service_account_file.__func__(DocumentProcessorServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentProcessorServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = functools.partial(type(DocumentProcessorServiceClient).get_transport_class, type(DocumentProcessorServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentProcessorServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service async 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. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = DocumentProcessorServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_process_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = await client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ProcessRequest, dict]]): - The request object. Request message for the - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - 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.AsyncRetry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.BatchProcessRequest, dict]]): - The request object. Request message for - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - """ - # 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.AsyncRetry( -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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - async def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we don't use - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - here, because it isn't paginated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_fetch_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.FetchProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.fetch_processor_types(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest, dict]]): - The request object. Request message for the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (:class:`str`): - Required. The location of processor types to list. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesAsyncPager: - r"""Lists the processor types that exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_list_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest, dict]]): - The request object. Request message for the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (:class:`str`): - Required. The location of processor types to list. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProcessorTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_get_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest, dict]]): - The request object. Request message for the - [GetProcessorType][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType] - method. - name (:class:`str`): - Required. The processor type resource - name. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.types.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.GetProcessorTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_processor_type, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsAsyncPager: - r"""Lists all processors which belong to this project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_list_processors(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorsRequest, dict]]): - The request object. Request message for list all - processors belongs to a project. - parent (:class:`str`): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ListProcessors][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProcessorsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_get_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorRequest, dict]]): - The request object. Request message for the - [GetProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor] - method. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def train_processor_version(self, - request: Optional[Union[document_processor_service.TrainProcessorVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor_version: Optional[processor.ProcessorVersion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1beta3.TrainProcessorVersionMetadata]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_train_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest, dict]]): - The request object. Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion] - method. - parent (:class:`str`): - Required. The parent (project, location and processor) - to create the new version for. Format: - ``projects/{project}/locations/{location}/processors/{processor}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor_version (:class:`google.cloud.documentai_v1beta3.types.ProcessorVersion`): - Required. The processor version to be - created. - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1beta3.types.TrainProcessorVersionResponse` The response for - [TrainProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, processor_version]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.TrainProcessorVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.train_processor_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.TrainProcessorVersionResponse, - metadata_type=document_processor_service.TrainProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def get_processor_version(self, - request: Optional[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_get_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest, dict]]): - The request object. Request message for the - [GetProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion] - method. - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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, - pretrained by Google internally or - uptrained by the customer. A processor - can only have one default version at a - time. Its document-processing behavior - is defined by that 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsAsyncPager: - r"""Lists all versions of a processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_list_processor_versions(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest, dict]]): - The request object. Request message for list all - processor versions belongs to a - processor. - parent (:class:`str`): - Required. The parent (project, location and processor) - to list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ListProcessorVersions][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProcessorVersionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_delete_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest, dict]]): - The request object. Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_deploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest, dict]]): - The request object. Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Undeploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest, dict]]): - The request object. Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] - provided. The processor will be at ``ENABLED`` state by default - after its creation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_create_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.CreateProcessorRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.CreateProcessorRequest, dict]]): - The request object. Request message for the - [CreateProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized - backend service. If the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] - isn't available in that region, the creation fails. - 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][google.cloud.documentai.v1beta3.Processor.type] - and - [Processor.display_name][google.cloud.documentai.v1beta3.Processor.display_name] - to be set. Also, the - [Processor.kms_key_name][google.cloud.documentai.v1beta3.Processor.kms_key_name] - field must be set if the processor is under CMEK. - - This corresponds to the ``processor`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_delete_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.DeleteProcessorRequest, dict]]): - The request object. Request message for the - [DeleteProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor] - 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - async def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Enables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_enable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.EnableProcessorRequest, dict]]): - The request object. Request message for the - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Disables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_disable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.DisableProcessorRequest, dict]]): - The request object. Request message for the - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - async def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_set_default_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest, dict]]): - The request object. Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_review_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ReviewDocumentRequest, dict]]): - The request object. Request message for the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - method. - human_review_config (:class:`str`): - Required. The resource name of the - [HumanReviewConfig][google.cloud.documentai.v1beta3.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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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 the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - 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.AsyncRetry( -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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # Done; return the response. - return response - - async def evaluate_processor_version(self, - request: Optional[Union[document_processor_service.EvaluateProcessorVersionRequest, dict]] = None, - *, - processor_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest, dict]]): - The request object. Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - against the supplied documents. - processor_version (:class:`str`): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to evaluate. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionResponse` Response of the - [EvaluateProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([processor_version]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.EvaluateProcessorVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.evaluate_processor_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("processor_version", request.processor_version), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document_processor_service.EvaluateProcessorVersionResponse, - metadata_type=document_processor_service.EvaluateProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def get_evaluation(self, - request: Optional[Union[document_processor_service.GetEvaluationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation.Evaluation: - r"""Retrieves a specific evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_get_evaluation(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_evaluation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetEvaluationRequest, dict]]): - The request object. Retrieves a specific Evaluation. - name (:class:`str`): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1beta3.Evaluation] - to get. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.types.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.GetEvaluationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_evaluation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_evaluations(self, - request: Optional[Union[document_processor_service.ListEvaluationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEvaluationsAsyncPager: - r"""Retrieves a set of evaluations for a given processor - version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - async def sample_list_evaluations(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListEvaluationsRequest, dict]]): - The request object. Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - parent (:class:`str`): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to list evaluations for. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsAsyncPager: - The response from ListEvaluations. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_processor_service.ListEvaluationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_evaluations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEvaluationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_processor_version(self, - request: Optional[Union[document_processor_service.ImportProcessorVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports a processor version from source 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_import_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ImportProcessorVersionRequest( - processor_version_source="processor_version_source_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ImportProcessorVersionRequest, dict]]): - The request object. The request message for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - The Document AI `Service - Agent `__ - of the destination project must have `Document AI Editor - role `__ - on the source project. - - The destination project is specified as part of the - [parent][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.parent] - field. The source project is specified as part of the - [source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.processor_version_source] - or - [external_processor_version_source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.external_processor_version_source] - field. - parent (:class:`str`): - Required. The destination processor name to create the - processor version in. 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_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.ImportProcessorVersionResponse` The response message for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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.ImportProcessorVersionRequest(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.import_processor_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ImportProcessorVersionResponse, - metadata_type=document_processor_service.ImportProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DocumentProcessorServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py deleted file mode 100644 index 004f097d4d04..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/client.py +++ /dev/null @@ -1,3631 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentProcessorServiceGrpcTransport -from .transports.grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .transports.rest import DocumentProcessorServiceRestTransport - - -class DocumentProcessorServiceClientMeta(type): - """Metaclass for the DocumentProcessorService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] - _transport_registry["grpc"] = DocumentProcessorServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentProcessorServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentProcessorServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentProcessorServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentProcessorServiceClient(metaclass=DocumentProcessorServiceClientMeta): - """Service to call Document AI 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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "documentai.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "documentai.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentProcessorServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DocumentProcessorServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentProcessorServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def evaluation_path(project: str,location: str,processor: str,processor_version: str,evaluation: str,) -> str: - """Returns a fully-qualified evaluation string.""" - return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}".format(project=project, location=location, processor=processor, processor_version=processor_version, evaluation=evaluation, ) - - @staticmethod - def parse_evaluation_path(path: str) -> Dict[str,str]: - """Parses a evaluation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)/evaluations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def human_review_config_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified human_review_config string.""" - return "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_human_review_config_path(path: str) -> Dict[str,str]: - """Parses a human_review_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/humanReviewConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified processor string.""" - return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_processor_path(path: str) -> Dict[str,str]: - """Parses a processor path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_type_path(project: str,location: str,processor_type: str,) -> str: - """Returns a fully-qualified processor_type string.""" - return "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - - @staticmethod - def parse_processor_type_path(path: str) -> Dict[str,str]: - """Parses a processor_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processorTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def processor_version_path(project: str,location: str,processor: str,processor_version: str,) -> str: - """Returns a fully-qualified processor_version string.""" - return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - - @staticmethod - def parse_processor_version_path(path: str) -> Dict[str,str]: - """Parses a processor_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - 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 - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - 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`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DocumentProcessorServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentProcessorServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document processor service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DocumentProcessorServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = DocumentProcessorServiceClient._read_environment_variables() - self._client_cert_source = DocumentProcessorServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DocumentProcessorServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._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. - transport_provided = isinstance(transport, DocumentProcessorServiceTransport) - if transport_provided: - # transport is a DocumentProcessorServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(DocumentProcessorServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DocumentProcessorServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - 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(cast(str, transport)) - self._transport = Transport( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def process_document(self, - request: Optional[Union[document_processor_service.ProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.ProcessResponse: - r"""Processes a single document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_process_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ProcessRequest( - inline_document=inline_document, - name="name_value", - ) - - # Make the request - response = client.process_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ProcessRequest, dict]): - The request object. Request message for the - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - 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 - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_process_documents(self, - request: Optional[Union[document_processor_service.BatchProcessRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_batch_process_documents(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.BatchProcessRequest( - name="name_value", - ) - - # Make the request - operation = client.batch_process_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.BatchProcessRequest, dict]): - The request object. Request message for - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - 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 - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - """ - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.BatchProcessResponse, - metadata_type=document_processor_service.BatchProcessMetadata, - ) - - # Done; return the response. - return response - - def fetch_processor_types(self, - request: Optional[Union[document_processor_service.FetchProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Fetches processor types. Note that we don't use - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - here, because it isn't 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 the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (str): - Required. The location of processor types to list. - 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 the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_processor_types(self, - request: Optional[Union[document_processor_service.ListProcessorTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorTypesPager: - r"""Lists the processor types that exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_list_processor_types(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest, dict]): - The request object. Request message for the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - parent (str): - Required. The location of processor types to list. - 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 the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProcessorTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor_type(self, - request: Optional[Union[document_processor_service.GetProcessorTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor_type.ProcessorType: - r"""Gets a processor type detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_get_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest, dict]): - The request object. Request message for the - [GetProcessorType][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType] - method. - name (str): - Required. The processor type resource - name. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.types.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.GetProcessorTypeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.GetProcessorTypeRequest): - request = document_processor_service.GetProcessorTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_processor_type] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_processors(self, - request: Optional[Union[document_processor_service.ListProcessorsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorsPager: - r"""Lists all processors which belong to this project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_list_processors(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processors(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListProcessorsRequest, dict]): - The request object. Request message for list all - processors belongs to a project. - parent (str): - Required. The parent (project and location) which owns - this collection of Processors. Format: - ``projects/{project}/locations/{location}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorsPager: - Response message for the - [ListProcessors][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProcessorsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_processor(self, - request: Optional[Union[document_processor_service.GetProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.Processor: - r"""Gets a processor detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_get_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetProcessorRequest, dict]): - The request object. Request message for the - [GetProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor] - method. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def train_processor_version(self, - request: Optional[Union[document_processor_service.TrainProcessorVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor_version: Optional[processor.ProcessorVersion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1beta3.TrainProcessorVersionMetadata]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_train_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest, dict]): - The request object. Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion] - method. - parent (str): - Required. The parent (project, location and processor) - to create the new version for. Format: - ``projects/{project}/locations/{location}/processors/{processor}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - processor_version (google.cloud.documentai_v1beta3.types.ProcessorVersion): - Required. The processor version to be - created. - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1beta3.types.TrainProcessorVersionResponse` The response for - [TrainProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, processor_version]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.TrainProcessorVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.TrainProcessorVersionRequest): - request = document_processor_service.TrainProcessorVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.train_processor_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.TrainProcessorVersionResponse, - metadata_type=document_processor_service.TrainProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def get_processor_version(self, - request: Optional[Union[document_processor_service.GetProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> processor.ProcessorVersion: - r"""Gets a processor version detail. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_get_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest, dict]): - The request object. Request message for the - [GetProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion] - method. - 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, - pretrained by Google internally or - uptrained by the customer. A processor - can only have one default version at a - time. Its document-processing behavior - is defined by that 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_processor_versions(self, - request: Optional[Union[document_processor_service.ListProcessorVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProcessorVersionsPager: - r"""Lists all versions of a processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_list_processor_versions(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListProcessorVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_processor_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest, dict]): - The request object. Request message for list all - processor versions belongs to a - processor. - parent (str): - Required. The parent (project, location and processor) - to list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorVersionsPager: - Response message for the - [ListProcessorVersions][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions] - method. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProcessorVersionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_processor_version(self, - request: Optional[Union[document_processor_service.DeleteProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor version, all artifacts under - the processor version will be deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_delete_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest, dict]): - The request object. Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def deploy_processor_version(self, - request: Optional[Union[document_processor_service.DeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_deploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest, dict]): - The request object. Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - 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 - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DeployProcessorVersionResponse, - metadata_type=document_processor_service.DeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def undeploy_processor_version(self, - request: Optional[Union[document_processor_service.UndeployProcessorVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Undeploys the processor version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_undeploy_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UndeployProcessorVersionRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest, dict]): - The request object. Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - 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 - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.UndeployProcessorVersionResponse, - metadata_type=document_processor_service.UndeployProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def create_processor(self, - request: Optional[Union[document_processor_service.CreateProcessorRequest, dict]] = None, - *, - parent: Optional[str] = None, - processor: Optional[gcd_processor.Processor] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_processor.Processor: - r"""Creates a processor from the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] - provided. 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 the - [CreateProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized - backend service. If the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] - isn't available in that region, the creation fails. - 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][google.cloud.documentai.v1beta3.Processor.type] - and - [Processor.display_name][google.cloud.documentai.v1beta3.Processor.display_name] - to be set. Also, the - [Processor.kms_key_name][google.cloud.documentai.v1beta3.Processor.kms_key_name] - field must be set if the processor is under CMEK. - - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_processor(self, - request: Optional[Union[document_processor_service.DeleteProcessorRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_delete_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DeleteProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.DeleteProcessorRequest, dict]): - The request object. Request message for the - [DeleteProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document_processor_service.DeleteProcessorMetadata, - ) - - # Done; return the response. - return response - - def enable_processor(self, - request: Optional[Union[document_processor_service.EnableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Enables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_enable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EnableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.enable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.EnableProcessorRequest, dict]): - The request object. Request message for the - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - 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 - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.EnableProcessorResponse, - metadata_type=document_processor_service.EnableProcessorMetadata, - ) - - # Done; return the response. - return response - - def disable_processor(self, - request: Optional[Union[document_processor_service.DisableProcessorRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Disables a processor - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_disable_processor(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.DisableProcessorRequest( - name="name_value", - ) - - # Make the request - operation = client.disable_processor(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.DisableProcessorRequest, dict]): - The request object. Request message for the - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - 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 - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.DisableProcessorResponse, - metadata_type=document_processor_service.DisableProcessorMetadata, - ) - - # Done; return the response. - return response - - def set_default_processor_version(self, - request: Optional[Union[document_processor_service.SetDefaultProcessorVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_set_default_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.SetDefaultProcessorVersionRequest( - processor="processor_value", - default_processor_version="default_processor_version_value", - ) - - # Make the request - operation = client.set_default_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest, dict]): - The request object. Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - 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 the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.SetDefaultProcessorVersionResponse, - metadata_type=document_processor_service.SetDefaultProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def review_document(self, - request: Optional[Union[document_processor_service.ReviewDocumentRequest, dict]] = None, - *, - human_review_config: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Send a document for Human Review. The input document - should be processed by the specified processor. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_review_document(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - inline_document = documentai_v1beta3.Document() - inline_document.uri = "uri_value" - - request = documentai_v1beta3.ReviewDocumentRequest( - inline_document=inline_document, - human_review_config="human_review_config_value", - ) - - # Make the request - operation = client.review_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ReviewDocumentRequest, dict]): - The request object. Request message for the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - method. - human_review_config (str): - Required. The resource name of the - [HumanReviewConfig][google.cloud.documentai.v1beta3.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 the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.ReviewDocumentResponse, - metadata_type=document_processor_service.ReviewDocumentOperationMetadata, - ) - - # Done; return the response. - return response - - def evaluate_processor_version(self, - request: Optional[Union[document_processor_service.EvaluateProcessorVersionRequest, dict]] = None, - *, - processor_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest, dict]): - The request object. Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - against the supplied documents. - processor_version (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to evaluate. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``processor_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionResponse` Response of the - [EvaluateProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([processor_version]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.EvaluateProcessorVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.EvaluateProcessorVersionRequest): - request = document_processor_service.EvaluateProcessorVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if processor_version is not None: - request.processor_version = processor_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.evaluate_processor_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("processor_version", request.processor_version), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document_processor_service.EvaluateProcessorVersionResponse, - metadata_type=document_processor_service.EvaluateProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def get_evaluation(self, - request: Optional[Union[document_processor_service.GetEvaluationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation.Evaluation: - r"""Retrieves a specific evaluation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_get_evaluation(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = client.get_evaluation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetEvaluationRequest, dict]): - The request object. Retrieves a specific Evaluation. - name (str): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1beta3.Evaluation] - to get. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.types.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.GetEvaluationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.GetEvaluationRequest): - request = document_processor_service.GetEvaluationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_evaluation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_evaluations(self, - request: Optional[Union[document_processor_service.ListEvaluationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEvaluationsPager: - r"""Retrieves a set of evaluations for a given processor - version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import documentai_v1beta3 - - def sample_list_evaluations(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListEvaluationsRequest, dict]): - The request object. Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - parent (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to list evaluations for. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsPager: - The response from ListEvaluations. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_processor_service.ListEvaluationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_processor_service.ListEvaluationsRequest): - request = document_processor_service.ListEvaluationsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_evaluations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListEvaluationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_processor_version(self, - request: Optional[Union[document_processor_service.ImportProcessorVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports a processor version from source 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_import_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ImportProcessorVersionRequest( - processor_version_source="processor_version_source_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_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.ImportProcessorVersionRequest, dict]): - The request object. The request message for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - The Document AI `Service - Agent `__ - of the destination project must have `Document AI Editor - role `__ - on the source project. - - The destination project is specified as part of the - [parent][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.parent] - field. The source project is specified as part of the - [source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.processor_version_source] - or - [external_processor_version_source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.external_processor_version_source] - field. - parent (str): - Required. The destination processor name to create the - processor version in. 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.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.ImportProcessorVersionResponse` The response message for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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.ImportProcessorVersionRequest. - # 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.ImportProcessorVersionRequest): - request = document_processor_service.ImportProcessorVersionRequest(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.import_processor_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ImportProcessorVersionResponse, - metadata_type=document_processor_service.ImportProcessorVersionMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentProcessorServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentProcessorServiceClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py deleted file mode 100644 index eace7694ea5d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py +++ /dev/null @@ -1,505 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor_type - - -class ListProcessorTypesPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListProcessorTypesResponse], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListProcessorTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[processor_type.ProcessorType]: - for page in self.pages: - yield from page.processor_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorTypesAsyncPager: - """A pager for iterating through ``list_processor_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorTypes`` requests and continue to iterate - through the ``processor_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListProcessorTypesResponse]], - request: document_processor_service.ListProcessorTypesRequest, - response: document_processor_service.ListProcessorTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorTypesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListProcessorTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[processor_type.ProcessorType]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListProcessorsResponse], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListProcessorsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[processor.Processor]: - for page in self.pages: - yield from page.processors - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorsAsyncPager: - """A pager for iterating through ``list_processors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processors`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessors`` requests and continue to iterate - through the ``processors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListProcessorsResponse]], - request: document_processor_service.ListProcessorsRequest, - response: document_processor_service.ListProcessorsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListProcessorsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListProcessorsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[processor.Processor]: - async def async_generator(): - async for page in self.pages: - for response in page.processors: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListProcessorVersionsResponse], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListProcessorVersionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[processor.ProcessorVersion]: - for page in self.pages: - yield from page.processor_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProcessorVersionsAsyncPager: - """A pager for iterating through ``list_processor_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``processor_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProcessorVersions`` requests and continue to iterate - through the ``processor_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListProcessorVersionsResponse]], - request: document_processor_service.ListProcessorVersionsRequest, - response: document_processor_service.ListProcessorVersionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListProcessorVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListProcessorVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListProcessorVersionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[processor.ProcessorVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.processor_versions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEvaluationsPager: - """A pager for iterating through ``list_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``evaluations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEvaluations`` requests and continue to iterate - through the ``evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., document_processor_service.ListEvaluationsResponse], - request: document_processor_service.ListEvaluationsRequest, - response: document_processor_service.ListEvaluationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListEvaluationsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListEvaluationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_processor_service.ListEvaluationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[evaluation.Evaluation]: - for page in self.pages: - yield from page.evaluations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEvaluationsAsyncPager: - """A pager for iterating through ``list_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``evaluations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEvaluations`` requests and continue to iterate - through the ``evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[document_processor_service.ListEvaluationsResponse]], - request: document_processor_service.ListEvaluationsRequest, - response: document_processor_service.ListEvaluationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.documentai_v1beta3.types.ListEvaluationsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListEvaluationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_processor_service.ListEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_processor_service.ListEvaluationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[evaluation.Evaluation]: - async def async_generator(): - async for page in self.pages: - for response in page.evaluations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py deleted file mode 100644 index ada8f5c0c0d9..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentProcessorServiceTransport -from .grpc import DocumentProcessorServiceGrpcTransport -from .grpc_asyncio import DocumentProcessorServiceGrpcAsyncIOTransport -from .rest import DocumentProcessorServiceRestTransport -from .rest import DocumentProcessorServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentProcessorServiceTransport]] -_transport_registry['grpc'] = DocumentProcessorServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentProcessorServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentProcessorServiceRestTransport - -__all__ = ( - 'DocumentProcessorServiceTransport', - 'DocumentProcessorServiceGrpcTransport', - 'DocumentProcessorServiceGrpcAsyncIOTransport', - 'DocumentProcessorServiceRestTransport', - 'DocumentProcessorServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py deleted file mode 100644 index 5d2f609ad8da..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py +++ /dev/null @@ -1,536 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentProcessorServiceTransport(abc.ABC): - """Abstract transport class for DocumentProcessorService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'documentai.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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 - - @property - def host(self): - return self._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=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.batch_process_documents: gapic_v1.method.wrap_method( - self.batch_process_documents, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.fetch_processor_types: gapic_v1.method.wrap_method( - self.fetch_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.list_processor_types: gapic_v1.method.wrap_method( - self.list_processor_types, - default_timeout=None, - client_info=client_info, - ), - self.get_processor_type: gapic_v1.method.wrap_method( - self.get_processor_type, - default_timeout=None, - client_info=client_info, - ), - self.list_processors: gapic_v1.method.wrap_method( - self.list_processors, - default_timeout=None, - client_info=client_info, - ), - self.get_processor: gapic_v1.method.wrap_method( - self.get_processor, - default_timeout=None, - client_info=client_info, - ), - self.train_processor_version: gapic_v1.method.wrap_method( - self.train_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.get_processor_version: gapic_v1.method.wrap_method( - self.get_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.list_processor_versions: gapic_v1.method.wrap_method( - self.list_processor_versions, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor_version: gapic_v1.method.wrap_method( - self.delete_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.deploy_processor_version: gapic_v1.method.wrap_method( - self.deploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.undeploy_processor_version: gapic_v1.method.wrap_method( - self.undeploy_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.create_processor: gapic_v1.method.wrap_method( - self.create_processor, - default_timeout=None, - client_info=client_info, - ), - self.delete_processor: gapic_v1.method.wrap_method( - self.delete_processor, - default_timeout=None, - client_info=client_info, - ), - self.enable_processor: gapic_v1.method.wrap_method( - self.enable_processor, - default_timeout=None, - client_info=client_info, - ), - self.disable_processor: gapic_v1.method.wrap_method( - self.disable_processor, - default_timeout=None, - client_info=client_info, - ), - self.set_default_processor_version: gapic_v1.method.wrap_method( - self.set_default_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.review_document: gapic_v1.method.wrap_method( - self.review_document, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.evaluate_processor_version: gapic_v1.method.wrap_method( - self.evaluate_processor_version, - default_timeout=None, - client_info=client_info, - ), - self.get_evaluation: gapic_v1.method.wrap_method( - self.get_evaluation, - default_timeout=None, - client_info=client_info, - ), - self.list_evaluations: gapic_v1.method.wrap_method( - self.list_evaluations, - default_timeout=None, - client_info=client_info, - ), - self.import_processor_version: gapic_v1.method.wrap_method( - self.import_processor_version, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - Union[ - document_processor_service.ProcessResponse, - Awaitable[document_processor_service.ProcessResponse] - ]]: - raise NotImplementedError() - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - Union[ - document_processor_service.FetchProcessorTypesResponse, - Awaitable[document_processor_service.FetchProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Union[ - document_processor_service.ListProcessorTypesResponse, - Awaitable[document_processor_service.ListProcessorTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Union[ - processor_type.ProcessorType, - Awaitable[processor_type.ProcessorType] - ]]: - raise NotImplementedError() - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Union[ - document_processor_service.ListProcessorsResponse, - Awaitable[document_processor_service.ListProcessorsResponse] - ]]: - raise NotImplementedError() - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Union[ - processor.Processor, - Awaitable[processor.Processor] - ]]: - raise NotImplementedError() - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Union[ - processor.ProcessorVersion, - Awaitable[processor.ProcessorVersion] - ]]: - raise NotImplementedError() - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Union[ - document_processor_service.ListProcessorVersionsResponse, - Awaitable[document_processor_service.ListProcessorVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Union[ - gcd_processor.Processor, - Awaitable[gcd_processor.Processor] - ]]: - raise NotImplementedError() - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - Union[ - evaluation.Evaluation, - Awaitable[evaluation.Evaluation] - ]]: - raise NotImplementedError() - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - Union[ - document_processor_service.ListEvaluationsResponse, - Awaitable[document_processor_service.ListEvaluationsResponse] - ]]: - raise NotImplementedError() - - @property - def import_processor_version(self) -> Callable[ - [document_processor_service.ImportProcessorVersionRequest], - 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/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py deleted file mode 100644 index 31297233e049..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py +++ /dev/null @@ -1,974 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentProcessorServiceGrpcTransport(DocumentProcessorServiceTransport): - """gRPC backend transport for DocumentProcessorService. - - Service to call Document AI to process documents according to - the processor's definition. Processors are built using - state-of-the-art Google AI such as natural language, computer - vision, and translation to extract structured information from - unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - r"""Return a callable for the process document method over gRPC. - - Processes a single document. - - Returns: - Callable[[~.ProcessRequest], - ~.ProcessResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'process_document' not in self._stubs: - self._stubs['process_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ProcessDocument', - request_serializer=document_processor_service.ProcessRequest.serialize, - response_deserializer=document_processor_service.ProcessResponse.deserialize, - ) - return self._stubs['process_document'] - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch process documents method over gRPC. - - LRO endpoint to batch process many documents. The output is - written to Cloud Storage as JSON in the [Document] format. - - Returns: - Callable[[~.BatchProcessRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_process_documents' not in self._stubs: - self._stubs['batch_process_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/BatchProcessDocuments', - request_serializer=document_processor_service.BatchProcessRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_process_documents'] - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - r"""Return a callable for the fetch processor types method over gRPC. - - Fetches processor types. Note that we don't use - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - here, because it isn't paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - ~.FetchProcessorTypesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - ~.ListProcessorTypesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - ~.ProcessorType]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - ~.ListProcessorsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - ~.Processor]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - return self._stubs['get_processor'] - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the train processor version method over gRPC. - - Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1beta3.TrainProcessorVersionMetadata]. - - Returns: - Callable[[~.TrainProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_processor_version' not in self._stubs: - self._stubs['train_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/TrainProcessorVersion', - request_serializer=document_processor_service.TrainProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_processor_version'] - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - ~.ProcessorVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - ~.ListProcessorVersionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] - provided. The processor will be at ``ENABLED`` state by default - after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - ~.Processor]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['review_document'] - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the evaluate processor version method over gRPC. - - Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - Returns: - Callable[[~.EvaluateProcessorVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'evaluate_processor_version' not in self._stubs: - self._stubs['evaluate_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/EvaluateProcessorVersion', - request_serializer=document_processor_service.EvaluateProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['evaluate_processor_version'] - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - evaluation.Evaluation]: - r"""Return a callable for the get evaluation method over gRPC. - - Retrieves a specific evaluation. - - Returns: - Callable[[~.GetEvaluationRequest], - ~.Evaluation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_evaluation' not in self._stubs: - self._stubs['get_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetEvaluation', - request_serializer=document_processor_service.GetEvaluationRequest.serialize, - response_deserializer=evaluation.Evaluation.deserialize, - ) - return self._stubs['get_evaluation'] - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - document_processor_service.ListEvaluationsResponse]: - r"""Return a callable for the list evaluations method over gRPC. - - Retrieves a set of evaluations for a given processor - version. - - Returns: - Callable[[~.ListEvaluationsRequest], - ~.ListEvaluationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_evaluations' not in self._stubs: - self._stubs['list_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListEvaluations', - request_serializer=document_processor_service.ListEvaluationsRequest.serialize, - response_deserializer=document_processor_service.ListEvaluationsResponse.deserialize, - ) - return self._stubs['list_evaluations'] - - @property - def import_processor_version(self) -> Callable[ - [document_processor_service.ImportProcessorVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the import processor version method over gRPC. - - Imports a processor version from source processor - version. - - Returns: - Callable[[~.ImportProcessorVersionRequest], - ~.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 'import_processor_version' not in self._stubs: - self._stubs['import_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ImportProcessorVersion', - request_serializer=document_processor_service.ImportProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_processor_version'] - - 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/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py deleted file mode 100644 index 70d5e759d4b0..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,973 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # 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 Document AI to process documents according to - the processor's definition. Processors are built using - state-of-the-art Google AI such as natural language, computer - vision, and translation to extract structured information from - unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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 don't use - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - here, because it isn't paginated. - - Returns: - Callable[[~.FetchProcessorTypesRequest], - Awaitable[~.FetchProcessorTypesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_processor_types' not in self._stubs: - self._stubs['fetch_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/FetchProcessorTypes', - request_serializer=document_processor_service.FetchProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.FetchProcessorTypesResponse.deserialize, - ) - return self._stubs['fetch_processor_types'] - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - Awaitable[document_processor_service.ListProcessorTypesResponse]]: - r"""Return a callable for the list processor types method over gRPC. - - Lists the processor types that exist. - - Returns: - Callable[[~.ListProcessorTypesRequest], - Awaitable[~.ListProcessorTypesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_types' not in self._stubs: - self._stubs['list_processor_types'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorTypes', - request_serializer=document_processor_service.ListProcessorTypesRequest.serialize, - response_deserializer=document_processor_service.ListProcessorTypesResponse.deserialize, - ) - return self._stubs['list_processor_types'] - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - Awaitable[processor_type.ProcessorType]]: - r"""Return a callable for the get processor type method over gRPC. - - Gets a processor type detail. - - Returns: - Callable[[~.GetProcessorTypeRequest], - Awaitable[~.ProcessorType]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_type' not in self._stubs: - self._stubs['get_processor_type'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorType', - request_serializer=document_processor_service.GetProcessorTypeRequest.serialize, - response_deserializer=processor_type.ProcessorType.deserialize, - ) - return self._stubs['get_processor_type'] - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - Awaitable[document_processor_service.ListProcessorsResponse]]: - r"""Return a callable for the list processors method over gRPC. - - Lists all processors which belong to this project. - - Returns: - Callable[[~.ListProcessorsRequest], - Awaitable[~.ListProcessorsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processors' not in self._stubs: - self._stubs['list_processors'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessors', - request_serializer=document_processor_service.ListProcessorsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorsResponse.deserialize, - ) - return self._stubs['list_processors'] - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - Awaitable[processor.Processor]]: - r"""Return a callable for the get processor method over gRPC. - - Gets a processor detail. - - Returns: - Callable[[~.GetProcessorRequest], - Awaitable[~.Processor]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor' not in self._stubs: - self._stubs['get_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessor', - request_serializer=document_processor_service.GetProcessorRequest.serialize, - response_deserializer=processor.Processor.deserialize, - ) - return self._stubs['get_processor'] - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the train processor version method over gRPC. - - Trains a new processor version. Operation metadata is returned - as - [TrainProcessorVersionMetadata][google.cloud.documentai.v1beta3.TrainProcessorVersionMetadata]. - - Returns: - Callable[[~.TrainProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_processor_version' not in self._stubs: - self._stubs['train_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/TrainProcessorVersion', - request_serializer=document_processor_service.TrainProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_processor_version'] - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - Awaitable[processor.ProcessorVersion]]: - r"""Return a callable for the get processor version method over gRPC. - - Gets a processor version detail. - - Returns: - Callable[[~.GetProcessorVersionRequest], - Awaitable[~.ProcessorVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_processor_version' not in self._stubs: - self._stubs['get_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetProcessorVersion', - request_serializer=document_processor_service.GetProcessorVersionRequest.serialize, - response_deserializer=processor.ProcessorVersion.deserialize, - ) - return self._stubs['get_processor_version'] - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - Awaitable[document_processor_service.ListProcessorVersionsResponse]]: - r"""Return a callable for the list processor versions method over gRPC. - - Lists all versions of a processor. - - Returns: - Callable[[~.ListProcessorVersionsRequest], - Awaitable[~.ListProcessorVersionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_processor_versions' not in self._stubs: - self._stubs['list_processor_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListProcessorVersions', - request_serializer=document_processor_service.ListProcessorVersionsRequest.serialize, - response_deserializer=document_processor_service.ListProcessorVersionsResponse.deserialize, - ) - return self._stubs['list_processor_versions'] - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor version method over gRPC. - - Deletes the processor version, all artifacts under - the processor version will be deleted. - - Returns: - Callable[[~.DeleteProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor_version' not in self._stubs: - self._stubs['delete_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessorVersion', - request_serializer=document_processor_service.DeleteProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor_version'] - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the deploy processor version method over gRPC. - - Deploys the processor version. - - Returns: - Callable[[~.DeployProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'deploy_processor_version' not in self._stubs: - self._stubs['deploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeployProcessorVersion', - request_serializer=document_processor_service.DeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_processor_version'] - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undeploy processor version method over gRPC. - - Undeploys the processor version. - - Returns: - Callable[[~.UndeployProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undeploy_processor_version' not in self._stubs: - self._stubs['undeploy_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/UndeployProcessorVersion', - request_serializer=document_processor_service.UndeployProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_processor_version'] - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - Awaitable[gcd_processor.Processor]]: - r"""Return a callable for the create processor method over gRPC. - - Creates a processor from the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] - provided. The processor will be at ``ENABLED`` state by default - after its creation. - - Returns: - Callable[[~.CreateProcessorRequest], - Awaitable[~.Processor]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_processor' not in self._stubs: - self._stubs['create_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/CreateProcessor', - request_serializer=document_processor_service.CreateProcessorRequest.serialize, - response_deserializer=gcd_processor.Processor.deserialize, - ) - return self._stubs['create_processor'] - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete processor method over gRPC. - - Deletes the processor, unloads all deployed model - artifacts if it was enabled and then deletes all - artifacts associated with this processor. - - Returns: - Callable[[~.DeleteProcessorRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_processor' not in self._stubs: - self._stubs['delete_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DeleteProcessor', - request_serializer=document_processor_service.DeleteProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_processor'] - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the enable processor method over gRPC. - - Enables a processor - - Returns: - Callable[[~.EnableProcessorRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'enable_processor' not in self._stubs: - self._stubs['enable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/EnableProcessor', - request_serializer=document_processor_service.EnableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['enable_processor'] - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the disable processor method over gRPC. - - Disables a processor - - Returns: - Callable[[~.DisableProcessorRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'disable_processor' not in self._stubs: - self._stubs['disable_processor'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/DisableProcessor', - request_serializer=document_processor_service.DisableProcessorRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['disable_processor'] - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set default processor version method over gRPC. - - Set the default (active) version of a - [Processor][google.cloud.documentai.v1beta3.Processor] that will - be used in - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - and - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - Returns: - Callable[[~.SetDefaultProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_default_processor_version' not in self._stubs: - self._stubs['set_default_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/SetDefaultProcessorVersion', - request_serializer=document_processor_service.SetDefaultProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_default_processor_version'] - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the review document method over gRPC. - - Send a document for Human Review. The input document - should be processed by the specified processor. - - Returns: - Callable[[~.ReviewDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'review_document' not in self._stubs: - self._stubs['review_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ReviewDocument', - request_serializer=document_processor_service.ReviewDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['review_document'] - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the evaluate processor version method over gRPC. - - Evaluates a ProcessorVersion against annotated - documents, producing an Evaluation. - - Returns: - Callable[[~.EvaluateProcessorVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'evaluate_processor_version' not in self._stubs: - self._stubs['evaluate_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/EvaluateProcessorVersion', - request_serializer=document_processor_service.EvaluateProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['evaluate_processor_version'] - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - Awaitable[evaluation.Evaluation]]: - r"""Return a callable for the get evaluation method over gRPC. - - Retrieves a specific evaluation. - - Returns: - Callable[[~.GetEvaluationRequest], - Awaitable[~.Evaluation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_evaluation' not in self._stubs: - self._stubs['get_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/GetEvaluation', - request_serializer=document_processor_service.GetEvaluationRequest.serialize, - response_deserializer=evaluation.Evaluation.deserialize, - ) - return self._stubs['get_evaluation'] - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - Awaitable[document_processor_service.ListEvaluationsResponse]]: - r"""Return a callable for the list evaluations method over gRPC. - - Retrieves a set of evaluations for a given processor - version. - - Returns: - Callable[[~.ListEvaluationsRequest], - Awaitable[~.ListEvaluationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_evaluations' not in self._stubs: - self._stubs['list_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ListEvaluations', - request_serializer=document_processor_service.ListEvaluationsRequest.serialize, - response_deserializer=document_processor_service.ListEvaluationsResponse.deserialize, - ) - return self._stubs['list_evaluations'] - - @property - def import_processor_version(self) -> Callable[ - [document_processor_service.ImportProcessorVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import processor version method over gRPC. - - Imports a processor version from source processor - version. - - Returns: - Callable[[~.ImportProcessorVersionRequest], - 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 'import_processor_version' not in self._stubs: - self._stubs['import_processor_version'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentProcessorService/ImportProcessorVersion', - request_serializer=document_processor_service.ImportProcessorVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_processor_version'] - - 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/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py deleted file mode 100644 index 9b525543eee6..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_processor_service/transports/rest.py +++ /dev/null @@ -1,3410 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentProcessorServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentProcessorServiceRestInterceptor: - """Interceptor for DocumentProcessorService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DocumentProcessorServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentProcessorServiceInterceptor(DocumentProcessorServiceRestInterceptor): - def pre_batch_process_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_process_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_deploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_deploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_disable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_disable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_enable_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_enable_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_evaluate_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_evaluate_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_fetch_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_fetch_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_evaluation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_evaluation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_evaluations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_evaluations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processors(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processors(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_processor_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_processor_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_process_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_process_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_review_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_review_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_default_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_default_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_train_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_train_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undeploy_processor_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undeploy_processor_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentProcessorServiceRestTransport(interceptor=MyCustomDocumentProcessorServiceInterceptor()) - client = DocumentProcessorServiceClient(transport=transport) - - - """ - def pre_batch_process_documents(self, request: document_processor_service.BatchProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.BatchProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_batch_process_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_process_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_create_processor(self, request: document_processor_service.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.CreateProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_create_processor(self, response: gcd_processor.Processor) -> gcd_processor.Processor: - """Post-rpc interceptor for create_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor(self, request: document_processor_service.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_delete_processor_version(self, request: document_processor_service.DeleteProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeleteProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_delete_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_deploy_processor_version(self, request: document_processor_service.DeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_deploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for deploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_disable_processor(self, request: document_processor_service.DisableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.DisableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for disable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_disable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for disable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_enable_processor(self, request: document_processor_service.EnableProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EnableProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for enable_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_enable_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for enable_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_evaluate_processor_version(self, request: document_processor_service.EvaluateProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.EvaluateProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_evaluate_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for evaluate_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_fetch_processor_types(self, request: document_processor_service.FetchProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.FetchProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_fetch_processor_types(self, response: document_processor_service.FetchProcessorTypesResponse) -> document_processor_service.FetchProcessorTypesResponse: - """Post-rpc interceptor for fetch_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_evaluation(self, request: document_processor_service.GetEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_evaluation(self, response: evaluation.Evaluation) -> evaluation.Evaluation: - """Post-rpc interceptor for get_evaluation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor(self, request: document_processor_service.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor(self, response: processor.Processor) -> processor.Processor: - """Post-rpc interceptor for get_processor - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_type(self, request: document_processor_service.GetProcessorTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_type(self, response: processor_type.ProcessorType) -> processor_type.ProcessorType: - """Post-rpc interceptor for get_processor_type - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_processor_version(self, request: document_processor_service.GetProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.GetProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_processor_version(self, response: processor.ProcessorVersion) -> processor.ProcessorVersion: - """Post-rpc interceptor for get_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_import_processor_version(self, request: document_processor_service.ImportProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ImportProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_import_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_evaluations(self, request: document_processor_service.ListEvaluationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_evaluations(self, response: document_processor_service.ListEvaluationsResponse) -> document_processor_service.ListEvaluationsResponse: - """Post-rpc interceptor for list_evaluations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processors(self, request: document_processor_service.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processors - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processors(self, response: document_processor_service.ListProcessorsResponse) -> document_processor_service.ListProcessorsResponse: - """Post-rpc interceptor for list_processors - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_types(self, request: document_processor_service.ListProcessorTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_types(self, response: document_processor_service.ListProcessorTypesResponse) -> document_processor_service.ListProcessorTypesResponse: - """Post-rpc interceptor for list_processor_types - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_processor_versions(self, request: document_processor_service.ListProcessorVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ListProcessorVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_processor_versions(self, response: document_processor_service.ListProcessorVersionsResponse) -> document_processor_service.ListProcessorVersionsResponse: - """Post-rpc interceptor for list_processor_versions - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_process_document(self, request: document_processor_service.ProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ProcessRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for process_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_process_document(self, response: document_processor_service.ProcessResponse) -> document_processor_service.ProcessResponse: - """Post-rpc interceptor for process_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_review_document(self, request: document_processor_service.ReviewDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.ReviewDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for review_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_review_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for review_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_set_default_processor_version(self, request: document_processor_service.SetDefaultProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.SetDefaultProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_set_default_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for set_default_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_train_processor_version(self, request: document_processor_service.TrainProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.TrainProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_train_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for train_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_undeploy_processor_version(self, request: document_processor_service.UndeployProcessorVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_processor_service.UndeployProcessorVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_undeploy_processor_version(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undeploy_processor_version - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentProcessorService server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the DocumentProcessorService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentProcessorServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentProcessorServiceRestInterceptor - - -class DocumentProcessorServiceRestTransport(DocumentProcessorServiceTransport): - """REST backend transport for DocumentProcessorService. - - Service to call Document AI to process documents according to - the processor's definition. Processors are built using - state-of-the-art Google AI such as natural language, computer - vision, and translation to extract structured information from - unstructured or semi-structured documents. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DocumentProcessorServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentProcessorServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchProcessDocuments(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("BatchProcessDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.BatchProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch process documents method over HTTP. - - Args: - request (~.document_processor_service.BatchProcessRequest): - The request object. Request message for - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:batchProcess', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:batchProcess', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_process_documents(request, metadata) - pb_request = document_processor_service.BatchProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_process_documents(resp) - return resp - - class _CreateProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("CreateProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.CreateProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_processor.Processor: - r"""Call the create processor method over HTTP. - - Args: - request (~.document_processor_service.CreateProcessorRequest): - The request object. Request message for the - [CreateProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized - backend service. If the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] - isn't available in that region, the creation fails. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{parent=projects/*/locations/*}/processors', - 'body': 'processor', - }, - ] - request, metadata = self._interceptor.pre_create_processor(request, metadata) - pb_request = document_processor_service.CreateProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_processor.Processor() - pb_resp = gcd_processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_processor(resp) - return resp - - class _DeleteProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorRequest): - The request object. Request message for the - [DeleteProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor(request, metadata) - pb_request = document_processor_service.DeleteProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor(resp) - return resp - - class _DeleteProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeleteProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeleteProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete processor version method over HTTP. - - Args: - request (~.document_processor_service.DeleteProcessorVersionRequest): - The request object. Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_processor_version(request, metadata) - pb_request = document_processor_service.DeleteProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_processor_version(resp) - return resp - - class _DeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the deploy processor version method over HTTP. - - Args: - request (~.document_processor_service.DeployProcessorVersionRequest): - The request object. Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_deploy_processor_version(request, metadata) - pb_request = document_processor_service.DeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_deploy_processor_version(resp) - return resp - - class _DisableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("DisableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.DisableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the disable processor method over HTTP. - - Args: - request (~.document_processor_service.DisableProcessorRequest): - The request object. Request message for the - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:disable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_disable_processor(request, metadata) - pb_request = document_processor_service.DisableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_disable_processor(resp) - return resp - - class _EnableProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EnableProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EnableProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the enable processor method over HTTP. - - Args: - request (~.document_processor_service.EnableProcessorRequest): - The request object. Request message for the - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:enable', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_enable_processor(request, metadata) - pb_request = document_processor_service.EnableProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_enable_processor(resp) - return resp - - class _EvaluateProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("EvaluateProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.EvaluateProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the evaluate processor - version method over HTTP. - - Args: - request (~.document_processor_service.EvaluateProcessorVersionRequest): - The request object. Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - against the supplied documents. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_evaluate_processor_version(request, metadata) - pb_request = document_processor_service.EvaluateProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_evaluate_processor_version(resp) - return resp - - class _FetchProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("FetchProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.FetchProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.FetchProcessorTypesResponse: - r"""Call the fetch processor types method over HTTP. - - Args: - request (~.document_processor_service.FetchProcessorTypesRequest): - The request object. Request message for the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.FetchProcessorTypesResponse: - Response message for the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*}:fetchProcessorTypes', - }, - ] - request, metadata = self._interceptor.pre_fetch_processor_types(request, metadata) - pb_request = document_processor_service.FetchProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.FetchProcessorTypesResponse() - pb_resp = document_processor_service.FetchProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_processor_types(resp) - return resp - - class _GetEvaluation(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetEvaluation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetEvaluationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> evaluation.Evaluation: - r"""Call the get evaluation method over HTTP. - - Args: - request (~.document_processor_service.GetEvaluationRequest): - The request object. Retrieves a specific Evaluation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.evaluation.Evaluation: - An evaluation of a ProcessorVersion's - performance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_evaluation(request, metadata) - pb_request = document_processor_service.GetEvaluationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = evaluation.Evaluation() - pb_resp = evaluation.Evaluation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_evaluation(resp) - return resp - - class _GetProcessor(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessor") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.Processor: - r"""Call the get processor method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorRequest): - The request object. Request message for the - [GetProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor] - 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: - ~.processor.Processor: - The first-class citizen for Document - AI. Each processor defines how to - extract structural information from a - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor(request, metadata) - pb_request = document_processor_service.GetProcessorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.Processor() - pb_resp = processor.Processor.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor(resp) - return resp - - class _GetProcessorType(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor_type.ProcessorType: - r"""Call the get processor type method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorTypeRequest): - The request object. Request message for the - [GetProcessorType][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType] - 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: - ~.processor_type.ProcessorType: - A processor type is responsible for - performing a certain document - understanding task on a certain type of - document. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processorTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_type(request, metadata) - pb_request = document_processor_service.GetProcessorTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor_type.ProcessorType() - pb_resp = processor_type.ProcessorType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_type(resp) - return resp - - class _GetProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("GetProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.GetProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> processor.ProcessorVersion: - r"""Call the get processor version method over HTTP. - - Args: - request (~.document_processor_service.GetProcessorVersionRequest): - The request object. Request message for the - [GetProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion] - 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: - ~.processor.ProcessorVersion: - A processor version is an - implementation of a processor. Each - processor can have multiple versions, - pretrained by Google internally or - uptrained by the customer. A processor - can only have one default version at a - time. Its document-processing behavior - is defined by that version. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_processor_version(request, metadata) - pb_request = document_processor_service.GetProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = processor.ProcessorVersion() - pb_resp = processor.ProcessorVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_processor_version(resp) - return resp - - class _ImportProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ImportProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ImportProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import processor version method over HTTP. - - Args: - request (~.document_processor_service.ImportProcessorVersionRequest): - The request object. The request message for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - The Document AI `Service - Agent `__ - of the destination project must have `Document AI Editor - role `__ - on the source project. - - The destination project is specified as part of the - [parent][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.parent] - field. The source project is specified as part of the - [source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.processor_version_source] - or - [external_processor_version_source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.external_processor_version_source] - field. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:importProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_processor_version(request, metadata) - pb_request = document_processor_service.ImportProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_processor_version(resp) - return resp - - class _ListEvaluations(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListEvaluations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListEvaluationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListEvaluationsResponse: - r"""Call the list evaluations method over HTTP. - - Args: - request (~.document_processor_service.ListEvaluationsRequest): - The request object. Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListEvaluationsResponse: - The response from ``ListEvaluations``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations', - }, - ] - request, metadata = self._interceptor.pre_list_evaluations(request, metadata) - pb_request = document_processor_service.ListEvaluationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListEvaluationsResponse() - pb_resp = document_processor_service.ListEvaluationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_evaluations(resp) - return resp - - class _ListProcessors(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessors") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorsResponse: - r"""Call the list processors method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorsRequest): - The request object. Request message for list all - processors belongs to a project. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListProcessorsResponse: - Response message for the - [ListProcessors][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*}/processors', - }, - ] - request, metadata = self._interceptor.pre_list_processors(request, metadata) - pb_request = document_processor_service.ListProcessorsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorsResponse() - pb_resp = document_processor_service.ListProcessorsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processors(resp) - return resp - - class _ListProcessorTypes(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorTypesResponse: - r"""Call the list processor types method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorTypesRequest): - The request object. Request message for the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be - added to an allowlist. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListProcessorTypesResponse: - Response message for the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*}/processorTypes', - }, - ] - request, metadata = self._interceptor.pre_list_processor_types(request, metadata) - pb_request = document_processor_service.ListProcessorTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorTypesResponse() - pb_resp = document_processor_service.ListProcessorTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_types(resp) - return resp - - class _ListProcessorVersions(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ListProcessorVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ListProcessorVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ListProcessorVersionsResponse: - r"""Call the list processor versions method over HTTP. - - Args: - request (~.document_processor_service.ListProcessorVersionsRequest): - The request object. Request message for list all - processor versions belongs to a - processor. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ListProcessorVersionsResponse: - Response message for the - [ListProcessorVersions][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions', - }, - ] - request, metadata = self._interceptor.pre_list_processor_versions(request, metadata) - pb_request = document_processor_service.ListProcessorVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ListProcessorVersionsResponse() - pb_resp = document_processor_service.ListProcessorVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_processor_versions(resp) - return resp - - class _ProcessDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ProcessDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ProcessRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_processor_service.ProcessResponse: - r"""Call the process document method over HTTP. - - Args: - request (~.document_processor_service.ProcessRequest): - The request object. Request message for the - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_processor_service.ProcessResponse: - Response message for the - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*}:process', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:process', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_process_document(request, metadata) - pb_request = document_processor_service.ProcessRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_processor_service.ProcessResponse() - pb_resp = document_processor_service.ProcessResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_process_document(resp) - return resp - - class _ReviewDocument(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("ReviewDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.ReviewDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the review document method over HTTP. - - Args: - request (~.document_processor_service.ReviewDocumentRequest): - The request object. Request message for the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_review_document(request, metadata) - pb_request = document_processor_service.ReviewDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_review_document(resp) - return resp - - class _SetDefaultProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("SetDefaultProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.SetDefaultProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the set default processor - version method over HTTP. - - Args: - request (~.document_processor_service.SetDefaultProcessorVersionRequest): - The request object. Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{processor=projects/*/locations/*/processors/*}:setDefaultProcessorVersion', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_default_processor_version(request, metadata) - pb_request = document_processor_service.SetDefaultProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_default_processor_version(resp) - return resp - - class _TrainProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("TrainProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.TrainProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the train processor version method over HTTP. - - Args: - request (~.document_processor_service.TrainProcessorVersionRequest): - The request object. Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:train', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_train_processor_version(request, metadata) - pb_request = document_processor_service.TrainProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_train_processor_version(resp) - return resp - - class _UndeployProcessorVersion(DocumentProcessorServiceRestStub): - def __hash__(self): - return hash("UndeployProcessorVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_processor_service.UndeployProcessorVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the undeploy processor - version method over HTTP. - - Args: - request (~.document_processor_service.UndeployProcessorVersionRequest): - The request object. Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_undeploy_processor_version(request, metadata) - pb_request = document_processor_service.UndeployProcessorVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_undeploy_processor_version(resp) - return resp - - @property - def batch_process_documents(self) -> Callable[ - [document_processor_service.BatchProcessRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchProcessDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_processor(self) -> Callable[ - [document_processor_service.CreateProcessorRequest], - gcd_processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor(self) -> Callable[ - [document_processor_service.DeleteProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_processor_version(self) -> Callable[ - [document_processor_service.DeleteProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def deploy_processor_version(self) -> Callable[ - [document_processor_service.DeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def disable_processor(self) -> Callable[ - [document_processor_service.DisableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DisableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def enable_processor(self) -> Callable[ - [document_processor_service.EnableProcessorRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EnableProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def evaluate_processor_version(self) -> Callable[ - [document_processor_service.EvaluateProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EvaluateProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_processor_types(self) -> Callable[ - [document_processor_service.FetchProcessorTypesRequest], - document_processor_service.FetchProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._FetchProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_evaluation(self) -> Callable[ - [document_processor_service.GetEvaluationRequest], - evaluation.Evaluation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor(self) -> Callable[ - [document_processor_service.GetProcessorRequest], - processor.Processor]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_type(self) -> Callable[ - [document_processor_service.GetProcessorTypeRequest], - processor_type.ProcessorType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_processor_version(self) -> Callable[ - [document_processor_service.GetProcessorVersionRequest], - processor.ProcessorVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_processor_version(self) -> Callable[ - [document_processor_service.ImportProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_evaluations(self) -> Callable[ - [document_processor_service.ListEvaluationsRequest], - document_processor_service.ListEvaluationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processors(self) -> Callable[ - [document_processor_service.ListProcessorsRequest], - document_processor_service.ListProcessorsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_types(self) -> Callable[ - [document_processor_service.ListProcessorTypesRequest], - document_processor_service.ListProcessorTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_processor_versions(self) -> Callable[ - [document_processor_service.ListProcessorVersionsRequest], - document_processor_service.ListProcessorVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProcessorVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def process_document(self) -> Callable[ - [document_processor_service.ProcessRequest], - document_processor_service.ProcessResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ProcessDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def review_document(self) -> Callable[ - [document_processor_service.ReviewDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ReviewDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_default_processor_version(self) -> Callable[ - [document_processor_service.SetDefaultProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetDefaultProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def train_processor_version(self) -> Callable[ - [document_processor_service.TrainProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TrainProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def undeploy_processor_version(self) -> Callable[ - [document_processor_service.UndeployProcessorVersionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UndeployProcessorVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DocumentProcessorServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*}/locations', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentProcessorServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentProcessorServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/__init__.py deleted file mode 100644 index 729ba971afe2..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DocumentServiceClient -from .async_client import DocumentServiceAsyncClient - -__all__ = ( - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/async_client.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/async_client.py deleted file mode 100644 index 7766c9edd433..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/async_client.py +++ /dev/null @@ -1,1337 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # 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_service import pagers -from google.cloud.documentai_v1beta3.types import dataset -from google.cloud.documentai_v1beta3.types import dataset as gcd_dataset -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import document_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .client import DocumentServiceClient - - -class DocumentServiceAsyncClient: - """Service to call Cloud DocumentAI to manage document - collection (dataset). - """ - - _client: DocumentServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DocumentServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DocumentServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DocumentServiceClient._DEFAULT_UNIVERSE - - dataset_path = staticmethod(DocumentServiceClient.dataset_path) - parse_dataset_path = staticmethod(DocumentServiceClient.parse_dataset_path) - dataset_schema_path = staticmethod(DocumentServiceClient.dataset_schema_path) - parse_dataset_schema_path = staticmethod(DocumentServiceClient.parse_dataset_schema_path) - schema_path = staticmethod(DocumentServiceClient.schema_path) - parse_schema_path = staticmethod(DocumentServiceClient.parse_schema_path) - common_billing_account_path = staticmethod(DocumentServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentServiceClient.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: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_info.__func__(DocumentServiceAsyncClient, 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: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_file.__func__(DocumentServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = functools.partial(type(DocumentServiceClient).get_transport_class, type(DocumentServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document service async 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, ~.DocumentServiceTransport]): 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. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = DocumentServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def update_dataset(self, - request: Optional[Union[document_service.UpdateDatasetRequest, dict]] = None, - *, - dataset: Optional[gcd_dataset.Dataset] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates metadata associated with a dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_update_dataset(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - dataset = documentai_v1beta3.Dataset() - dataset.state = "INITIALIZED" - - request = documentai_v1beta3.UpdateDatasetRequest( - dataset=dataset, - ) - - # Make the request - operation = client.update_dataset(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.UpdateDatasetRequest, dict]]): - The request object. - dataset (:class:`google.cloud.documentai_v1beta3.types.Dataset`): - Required. The ``name`` field of the ``Dataset`` is used - to identify the resource to be updated. - - This corresponds to the ``dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The update mask applies to the - resource. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.Dataset` A singleton resource under a - [Processor][google.cloud.documentai.v1beta3.Processor] - which configures a collection of documents. - - """ - # 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([dataset, update_mask]) - 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_service.UpdateDatasetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_dataset, - 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(( - ("dataset.name", request.dataset.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcd_dataset.Dataset, - metadata_type=document_service.UpdateDatasetOperationMetadata, - ) - - # Done; return the response. - return response - - async def import_documents(self, - request: Optional[Union[document_service.ImportDocumentsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Import documents into a dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_import_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - batch_documents_import_configs = documentai_v1beta3.BatchDocumentsImportConfig() - batch_documents_import_configs.dataset_split = "DATASET_SPLIT_UNASSIGNED" - - request = documentai_v1beta3.ImportDocumentsRequest( - dataset="dataset_value", - batch_documents_import_configs=batch_documents_import_configs, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ImportDocumentsRequest, dict]]): - The request object. - dataset (:class:`str`): - Required. The dataset resource name. - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.ImportDocumentsResponse` - Response of the import document operation. - - """ - # 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([dataset]) - 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_service.ImportDocumentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_documents, - 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(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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_service.ImportDocumentsResponse, - metadata_type=document_service.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_service.GetDocumentResponse: - r"""Returns relevant fields present in the requested - 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_get_document(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - document_id = documentai_v1beta3.DocumentId() - document_id.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.GetDocumentRequest( - dataset="dataset_value", - document_id=document_id, - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetDocumentRequest, dict]]): - The request object. - dataset (:class:`str`): - Required. The resource name of the - dataset that the document belongs to . - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.GetDocumentResponse: - - """ - # 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([dataset]) - 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_service.GetDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # 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_document, - 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(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsAsyncPager: - r"""Returns a list of documents present in the dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListDocumentsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.ListDocumentsRequest, dict]]): - The request object. - dataset (:class:`str`): - Required. The resource name of the - dataset to be listed. Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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_service.pagers.ListDocumentsAsyncPager: - 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([dataset]) - 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_service.ListDocumentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # 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_documents, - 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(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListDocumentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_delete_documents(self, - request: Optional[Union[document_service.BatchDeleteDocumentsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a set of documents. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_delete_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - dataset_documents = documentai_v1beta3.BatchDatasetDocuments() - dataset_documents.individual_document_ids.document_ids.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.BatchDeleteDocumentsRequest( - dataset="dataset_value", - dataset_documents=dataset_documents, - ) - - # Make the request - operation = client.batch_delete_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.BatchDeleteDocumentsRequest, dict]]): - The request object. - dataset (:class:`str`): - Required. The dataset resource name. - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.BatchDeleteDocumentsResponse` - Response of the delete documents operation. - - """ - # 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([dataset]) - 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_service.BatchDeleteDocumentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # 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_delete_documents, - 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(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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_service.BatchDeleteDocumentsResponse, - metadata_type=document_service.BatchDeleteDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def get_dataset_schema(self, - request: Optional[Union[document_service.GetDatasetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.DatasetSchema: - r"""Gets the ``DatasetSchema`` of a ``Dataset``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetDatasetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_dataset_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.GetDatasetSchemaRequest, dict]]): - The request object. Request for ``GetDatasetSchema``. - name (:class:`str`): - Required. The dataset schema resource - name. Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset/datasetSchema - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.DatasetSchema: - Dataset Schema. - """ - # 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_service.GetDatasetSchemaRequest(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_dataset_schema, - 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_dataset_schema(self, - request: Optional[Union[document_service.UpdateDatasetSchemaRequest, dict]] = None, - *, - dataset_schema: Optional[dataset.DatasetSchema] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.DatasetSchema: - r"""Updates a ``DatasetSchema``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_update_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UpdateDatasetSchemaRequest( - ) - - # Make the request - response = await client.update_dataset_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.documentai_v1beta3.types.UpdateDatasetSchemaRequest, dict]]): - The request object. Request for ``UpdateDatasetSchema``. - dataset_schema (:class:`google.cloud.documentai_v1beta3.types.DatasetSchema`): - Required. The name field of the ``DatasetSchema`` is - used to identify the resource to be updated. - - This corresponds to the ``dataset_schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The update mask applies to the - resource. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (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.DatasetSchema: - Dataset Schema. - """ - # 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([dataset_schema, update_mask]) - 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_service.UpdateDatasetSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset_schema is not None: - request.dataset_schema = dataset_schema - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_dataset_schema, - 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(( - ("dataset_schema.name", request.dataset_schema.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DocumentServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/client.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/client.py deleted file mode 100644 index 7f6f67b6f8a2..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/client.py +++ /dev/null @@ -1,1702 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # 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_service import pagers -from google.cloud.documentai_v1beta3.types import dataset -from google.cloud.documentai_v1beta3.types import dataset as gcd_dataset -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import document_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentServiceGrpcTransport -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .transports.rest import DocumentServiceRestTransport - - -class DocumentServiceClientMeta(type): - """Metaclass for the DocumentService 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[DocumentServiceTransport]] - _transport_registry["grpc"] = DocumentServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentServiceTransport]: - """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 DocumentServiceClient(metaclass=DocumentServiceClientMeta): - """Service to call Cloud DocumentAI to manage document - collection (dataset). - """ - - @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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "documentai.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "documentai.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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: - DocumentServiceClient: 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: - DocumentServiceClient: 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) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def dataset_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified dataset string.""" - return "projects/{project}/locations/{location}/processors/{processor}/dataset".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_dataset_path(path: str) -> Dict[str,str]: - """Parses a dataset path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/dataset$", path) - return m.groupdict() if m else {} - - @staticmethod - def dataset_schema_path(project: str,location: str,processor: str,) -> str: - """Returns a fully-qualified dataset_schema string.""" - return "projects/{project}/locations/{location}/processors/{processor}/dataset/datasetSchema".format(project=project, location=location, processor=processor, ) - - @staticmethod - def parse_dataset_schema_path(path: str) -> Dict[str,str]: - """Parses a dataset_schema path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/dataset/datasetSchema$", path) - return m.groupdict() if m else {} - - @staticmethod - def schema_path(project: str,location: str,schema: str,) -> str: - """Returns a fully-qualified schema string.""" - return "projects/{project}/locations/{location}/schemas/{schema}".format(project=project, location=location, schema=schema, ) - - @staticmethod - def parse_schema_path(path: str) -> Dict[str,str]: - """Parses a schema path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/schemas/(?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): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - 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 - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - 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`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = DocumentServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DocumentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = DocumentServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DocumentServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DocumentServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentServiceTransport]] = 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 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, DocumentServiceTransport]): 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. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = DocumentServiceClient._read_environment_variables() - self._client_cert_source = DocumentServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DocumentServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._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. - transport_provided = isinstance(transport, DocumentServiceTransport) - if transport_provided: - # transport is a DocumentServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(DocumentServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DocumentServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - 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(cast(str, transport)) - self._transport = Transport( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def update_dataset(self, - request: Optional[Union[document_service.UpdateDatasetRequest, dict]] = None, - *, - dataset: Optional[gcd_dataset.Dataset] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates metadata associated with a dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_update_dataset(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - dataset = documentai_v1beta3.Dataset() - dataset.state = "INITIALIZED" - - request = documentai_v1beta3.UpdateDatasetRequest( - dataset=dataset, - ) - - # Make the request - operation = client.update_dataset(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.UpdateDatasetRequest, dict]): - The request object. - dataset (google.cloud.documentai_v1beta3.types.Dataset): - Required. The ``name`` field of the ``Dataset`` is used - to identify the resource to be updated. - - This corresponds to the ``dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The update mask applies to the - resource. - - This corresponds to the ``update_mask`` 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.Dataset` A singleton resource under a - [Processor][google.cloud.documentai.v1beta3.Processor] - which configures a collection of documents. - - """ - # 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([dataset, update_mask]) - 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_service.UpdateDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.UpdateDatasetRequest): - request = document_service.UpdateDatasetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_dataset] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset.name", request.dataset.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcd_dataset.Dataset, - metadata_type=document_service.UpdateDatasetOperationMetadata, - ) - - # Done; return the response. - return response - - def import_documents(self, - request: Optional[Union[document_service.ImportDocumentsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Import documents into a dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_import_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - batch_documents_import_configs = documentai_v1beta3.BatchDocumentsImportConfig() - batch_documents_import_configs.dataset_split = "DATASET_SPLIT_UNASSIGNED" - - request = documentai_v1beta3.ImportDocumentsRequest( - dataset="dataset_value", - batch_documents_import_configs=batch_documents_import_configs, - ) - - # Make the request - operation = client.import_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.ImportDocumentsRequest, dict]): - The request object. - dataset (str): - Required. The dataset resource name. - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` 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.ImportDocumentsResponse` - Response of the import document operation. - - """ - # 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([dataset]) - 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_service.ImportDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.ImportDocumentsRequest): - request = document_service.ImportDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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_service.ImportDocumentsResponse, - metadata_type=document_service.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document_service.GetDocumentResponse: - r"""Returns relevant fields present in the requested - 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_get_document(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - document_id = documentai_v1beta3.DocumentId() - document_id.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.GetDocumentRequest( - dataset="dataset_value", - document_id=document_id, - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetDocumentRequest, dict]): - The request object. - dataset (str): - Required. The resource name of the - dataset that the document belongs to . - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` 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.GetDocumentResponse: - - """ - # 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([dataset]) - 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_service.GetDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.GetDocumentRequest): - request = document_service.GetDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsPager: - r"""Returns a list of documents present in the dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListDocumentsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.ListDocumentsRequest, dict]): - The request object. - dataset (str): - Required. The resource name of the - dataset to be listed. Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` 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_service.pagers.ListDocumentsPager: - 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([dataset]) - 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_service.ListDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.ListDocumentsRequest): - request = document_service.ListDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListDocumentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_delete_documents(self, - request: Optional[Union[document_service.BatchDeleteDocumentsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a set of documents. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_delete_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - dataset_documents = documentai_v1beta3.BatchDatasetDocuments() - dataset_documents.individual_document_ids.document_ids.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.BatchDeleteDocumentsRequest( - dataset="dataset_value", - dataset_documents=dataset_documents, - ) - - # Make the request - operation = client.batch_delete_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.BatchDeleteDocumentsRequest, dict]): - The request object. - dataset (str): - Required. The dataset resource name. - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - - This corresponds to the ``dataset`` 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.BatchDeleteDocumentsResponse` - Response of the delete documents operation. - - """ - # 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([dataset]) - 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_service.BatchDeleteDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.BatchDeleteDocumentsRequest): - request = document_service.BatchDeleteDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset", request.dataset), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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_service.BatchDeleteDocumentsResponse, - metadata_type=document_service.BatchDeleteDocumentsMetadata, - ) - - # Done; return the response. - return response - - def get_dataset_schema(self, - request: Optional[Union[document_service.GetDatasetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.DatasetSchema: - r"""Gets the ``DatasetSchema`` of a ``Dataset``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetDatasetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_dataset_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.GetDatasetSchemaRequest, dict]): - The request object. Request for ``GetDatasetSchema``. - name (str): - Required. The dataset schema resource - name. Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset/datasetSchema - - 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.DatasetSchema: - Dataset Schema. - """ - # 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_service.GetDatasetSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.GetDatasetSchemaRequest): - request = document_service.GetDatasetSchemaRequest(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_dataset_schema] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_dataset_schema(self, - request: Optional[Union[document_service.UpdateDatasetSchemaRequest, dict]] = None, - *, - dataset_schema: Optional[dataset.DatasetSchema] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.DatasetSchema: - r"""Updates a ``DatasetSchema``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when 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_update_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UpdateDatasetSchemaRequest( - ) - - # Make the request - response = client.update_dataset_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.documentai_v1beta3.types.UpdateDatasetSchemaRequest, dict]): - The request object. Request for ``UpdateDatasetSchema``. - dataset_schema (google.cloud.documentai_v1beta3.types.DatasetSchema): - Required. The name field of the ``DatasetSchema`` is - used to identify the resource to be updated. - - This corresponds to the ``dataset_schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The update mask applies to the - resource. - - This corresponds to the ``update_mask`` 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.DatasetSchema: - Dataset Schema. - """ - # 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([dataset_schema, update_mask]) - 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_service.UpdateDatasetSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.UpdateDatasetSchemaRequest): - request = document_service.UpdateDatasetSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset_schema is not None: - request.dataset_schema = dataset_schema - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_dataset_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset_schema.name", request.dataset_schema.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceClient", -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/pagers.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/pagers.py deleted file mode 100644 index 6f2117376f12..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_service - - -class ListDocumentsPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListDocumentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``document_metadata`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``document_metadata`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListDocumentsResponse` - 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_service.ListDocumentsResponse], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - 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.ListDocumentsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListDocumentsResponse): - 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_service.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_service.ListDocumentsResponse]: - 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[document_service.DocumentMetadata]: - for page in self.pages: - yield from page.document_metadata - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDocumentsAsyncPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.documentai_v1beta3.types.ListDocumentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``document_metadata`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``document_metadata`` field on the - corresponding responses. - - All the usual :class:`google.cloud.documentai_v1beta3.types.ListDocumentsResponse` - 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_service.ListDocumentsResponse]], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - 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.ListDocumentsRequest): - The initial request object. - response (google.cloud.documentai_v1beta3.types.ListDocumentsResponse): - 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_service.ListDocumentsRequest(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_service.ListDocumentsResponse]: - 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[document_service.DocumentMetadata]: - async def async_generator(): - async for page in self.pages: - for response in page.document_metadata: - 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/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/__init__.py deleted file mode 100644 index 7412085409de..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DocumentServiceTransport -from .grpc import DocumentServiceGrpcTransport -from .grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .rest import DocumentServiceRestTransport -from .rest import DocumentServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentServiceTransport]] -_transport_registry['grpc'] = DocumentServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentServiceRestTransport - -__all__ = ( - 'DocumentServiceTransport', - 'DocumentServiceGrpcTransport', - 'DocumentServiceGrpcAsyncIOTransport', - 'DocumentServiceRestTransport', - 'DocumentServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/base.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/base.py deleted file mode 100644 index ada1705fa09c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/base.py +++ /dev/null @@ -1,288 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.documentai_v1beta3 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.documentai_v1beta3.types import dataset -from google.cloud.documentai_v1beta3.types import document_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentServiceTransport(abc.ABC): - """Abstract transport class for DocumentService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'documentai.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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 - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.update_dataset: gapic_v1.method.wrap_method( - self.update_dataset, - default_timeout=None, - client_info=client_info, - ), - self.import_documents: gapic_v1.method.wrap_method( - self.import_documents, - default_timeout=None, - client_info=client_info, - ), - self.get_document: gapic_v1.method.wrap_method( - self.get_document, - default_timeout=None, - client_info=client_info, - ), - self.list_documents: gapic_v1.method.wrap_method( - self.list_documents, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_documents: gapic_v1.method.wrap_method( - self.batch_delete_documents, - default_timeout=None, - client_info=client_info, - ), - self.get_dataset_schema: gapic_v1.method.wrap_method( - self.get_dataset_schema, - default_timeout=None, - client_info=client_info, - ), - self.update_dataset_schema: gapic_v1.method.wrap_method( - self.update_dataset_schema, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def update_dataset(self) -> Callable[ - [document_service.UpdateDatasetRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_documents(self) -> Callable[ - [document_service.ImportDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Union[ - document_service.GetDocumentResponse, - Awaitable[document_service.GetDocumentResponse] - ]]: - raise NotImplementedError() - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Union[ - document_service.ListDocumentsResponse, - Awaitable[document_service.ListDocumentsResponse] - ]]: - raise NotImplementedError() - - @property - def batch_delete_documents(self) -> Callable[ - [document_service.BatchDeleteDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_dataset_schema(self) -> Callable[ - [document_service.GetDatasetSchemaRequest], - Union[ - dataset.DatasetSchema, - Awaitable[dataset.DatasetSchema] - ]]: - raise NotImplementedError() - - @property - def update_dataset_schema(self) -> Callable[ - [document_service.UpdateDatasetSchemaRequest], - Union[ - dataset.DatasetSchema, - Awaitable[dataset.DatasetSchema] - ]]: - 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__ = ( - 'DocumentServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/grpc.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/grpc.py deleted file mode 100644 index 95edc3f6b0bb..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/grpc.py +++ /dev/null @@ -1,533 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 dataset -from google.cloud.documentai_v1beta3.types import document_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentServiceGrpcTransport(DocumentServiceTransport): - """gRPC backend transport for DocumentService. - - Service to call Cloud DocumentAI to manage document - collection (dataset). - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def update_dataset(self) -> Callable[ - [document_service.UpdateDatasetRequest], - operations_pb2.Operation]: - r"""Return a callable for the update dataset method over gRPC. - - Updates metadata associated with a dataset. - - Returns: - Callable[[~.UpdateDatasetRequest], - ~.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 'update_dataset' not in self._stubs: - self._stubs['update_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/UpdateDataset', - request_serializer=document_service.UpdateDatasetRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_dataset'] - - @property - def import_documents(self) -> Callable[ - [document_service.ImportDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import documents method over gRPC. - - Import documents into a dataset. - - Returns: - Callable[[~.ImportDocumentsRequest], - ~.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 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/ImportDocuments', - request_serializer=document_service.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document_service.GetDocumentResponse]: - r"""Return a callable for the get document method over gRPC. - - Returns relevant fields present in the requested - document. - - Returns: - Callable[[~.GetDocumentRequest], - ~.GetDocumentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document_service.GetDocumentResponse.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - r"""Return a callable for the list documents method over gRPC. - - Returns a list of documents present in the dataset. - - Returns: - Callable[[~.ListDocumentsRequest], - ~.ListDocumentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def batch_delete_documents(self) -> Callable[ - [document_service.BatchDeleteDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch delete documents method over gRPC. - - Deletes a set of documents. - - Returns: - Callable[[~.BatchDeleteDocumentsRequest], - ~.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_delete_documents' not in self._stubs: - self._stubs['batch_delete_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/BatchDeleteDocuments', - request_serializer=document_service.BatchDeleteDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_documents'] - - @property - def get_dataset_schema(self) -> Callable[ - [document_service.GetDatasetSchemaRequest], - dataset.DatasetSchema]: - r"""Return a callable for the get dataset schema method over gRPC. - - Gets the ``DatasetSchema`` of a ``Dataset``. - - Returns: - Callable[[~.GetDatasetSchemaRequest], - ~.DatasetSchema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset_schema' not in self._stubs: - self._stubs['get_dataset_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/GetDatasetSchema', - request_serializer=document_service.GetDatasetSchemaRequest.serialize, - response_deserializer=dataset.DatasetSchema.deserialize, - ) - return self._stubs['get_dataset_schema'] - - @property - def update_dataset_schema(self) -> Callable[ - [document_service.UpdateDatasetSchemaRequest], - dataset.DatasetSchema]: - r"""Return a callable for the update dataset schema method over gRPC. - - Updates a ``DatasetSchema``. - - Returns: - Callable[[~.UpdateDatasetSchemaRequest], - ~.DatasetSchema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_dataset_schema' not in self._stubs: - self._stubs['update_dataset_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/UpdateDatasetSchema', - request_serializer=document_service.UpdateDatasetSchemaRequest.serialize, - response_deserializer=dataset.DatasetSchema.deserialize, - ) - return self._stubs['update_dataset_schema'] - - 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__ = ( - 'DocumentServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/grpc_asyncio.py deleted file mode 100644 index 36b3fa9a07b8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,532 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 dataset -from google.cloud.documentai_v1beta3.types import document_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentServiceGrpcTransport - - -class DocumentServiceGrpcAsyncIOTransport(DocumentServiceTransport): - """gRPC AsyncIO backend transport for DocumentService. - - Service to call Cloud DocumentAI to manage document - collection (dataset). - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - 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 update_dataset(self) -> Callable[ - [document_service.UpdateDatasetRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update dataset method over gRPC. - - Updates metadata associated with a dataset. - - Returns: - Callable[[~.UpdateDatasetRequest], - 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 'update_dataset' not in self._stubs: - self._stubs['update_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/UpdateDataset', - request_serializer=document_service.UpdateDatasetRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_dataset'] - - @property - def import_documents(self) -> Callable[ - [document_service.ImportDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import documents method over gRPC. - - Import documents into a dataset. - - Returns: - Callable[[~.ImportDocumentsRequest], - 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 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/ImportDocuments', - request_serializer=document_service.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Awaitable[document_service.GetDocumentResponse]]: - r"""Return a callable for the get document method over gRPC. - - Returns relevant fields present in the requested - document. - - Returns: - Callable[[~.GetDocumentRequest], - Awaitable[~.GetDocumentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document_service.GetDocumentResponse.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Awaitable[document_service.ListDocumentsResponse]]: - r"""Return a callable for the list documents method over gRPC. - - Returns a list of documents present in the dataset. - - Returns: - Callable[[~.ListDocumentsRequest], - Awaitable[~.ListDocumentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def batch_delete_documents(self) -> Callable[ - [document_service.BatchDeleteDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch delete documents method over gRPC. - - Deletes a set of documents. - - Returns: - Callable[[~.BatchDeleteDocumentsRequest], - 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_delete_documents' not in self._stubs: - self._stubs['batch_delete_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/BatchDeleteDocuments', - request_serializer=document_service.BatchDeleteDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_documents'] - - @property - def get_dataset_schema(self) -> Callable[ - [document_service.GetDatasetSchemaRequest], - Awaitable[dataset.DatasetSchema]]: - r"""Return a callable for the get dataset schema method over gRPC. - - Gets the ``DatasetSchema`` of a ``Dataset``. - - Returns: - Callable[[~.GetDatasetSchemaRequest], - Awaitable[~.DatasetSchema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset_schema' not in self._stubs: - self._stubs['get_dataset_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/GetDatasetSchema', - request_serializer=document_service.GetDatasetSchemaRequest.serialize, - response_deserializer=dataset.DatasetSchema.deserialize, - ) - return self._stubs['get_dataset_schema'] - - @property - def update_dataset_schema(self) -> Callable[ - [document_service.UpdateDatasetSchemaRequest], - Awaitable[dataset.DatasetSchema]]: - r"""Return a callable for the update dataset schema method over gRPC. - - Updates a ``DatasetSchema``. - - Returns: - Callable[[~.UpdateDatasetSchemaRequest], - Awaitable[~.DatasetSchema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_dataset_schema' not in self._stubs: - self._stubs['update_dataset_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.documentai.v1beta3.DocumentService/UpdateDatasetSchema', - request_serializer=document_service.UpdateDatasetSchemaRequest.serialize, - response_deserializer=dataset.DatasetSchema.deserialize, - ) - return self._stubs['update_dataset_schema'] - - 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__ = ( - 'DocumentServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/rest.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/rest.py deleted file mode 100644 index dec3895fd32f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/services/document_service/transports/rest.py +++ /dev/null @@ -1,1485 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.documentai_v1beta3.types import dataset -from google.cloud.documentai_v1beta3.types import document_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentServiceRestInterceptor: - """Interceptor for DocumentService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DocumentServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentServiceInterceptor(DocumentServiceRestInterceptor): - def pre_batch_delete_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_delete_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_dataset_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_dataset_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_dataset(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_dataset(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_dataset_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_dataset_schema(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentServiceRestTransport(interceptor=MyCustomDocumentServiceInterceptor()) - client = DocumentServiceClient(transport=transport) - - - """ - def pre_batch_delete_documents(self, request: document_service.BatchDeleteDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.BatchDeleteDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_delete_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_batch_delete_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_delete_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_get_dataset_schema(self, request: document_service.GetDatasetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDatasetSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_dataset_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_get_dataset_schema(self, response: dataset.DatasetSchema) -> dataset.DatasetSchema: - """Post-rpc interceptor for get_dataset_schema - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_get_document(self, request: document_service.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_get_document(self, response: document_service.GetDocumentResponse) -> document_service.GetDocumentResponse: - """Post-rpc interceptor for get_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_import_documents(self, request: document_service.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_documents(self, request: document_service.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ListDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_list_documents(self, response: document_service.ListDocumentsResponse) -> document_service.ListDocumentsResponse: - """Post-rpc interceptor for list_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_update_dataset(self, request: document_service.UpdateDatasetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDatasetRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_dataset - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_update_dataset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_dataset - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_update_dataset_schema(self, request: document_service.UpdateDatasetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDatasetSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_dataset_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_update_dataset_schema(self, response: dataset.DatasetSchema) -> dataset.DatasetSchema: - """Post-rpc interceptor for update_dataset_schema - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentServiceRestInterceptor - - -class DocumentServiceRestTransport(DocumentServiceTransport): - """REST backend transport for DocumentService. - - Service to call Cloud DocumentAI to manage document - collection (dataset). - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'documentai.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DocumentServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'documentai.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', - }, - { - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchDeleteDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("BatchDeleteDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.BatchDeleteDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch delete documents method over HTTP. - - Args: - request (~.document_service.BatchDeleteDocumentsRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:batchDeleteDocuments', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_delete_documents(request, metadata) - pb_request = document_service.BatchDeleteDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_delete_documents(resp) - return resp - - class _GetDatasetSchema(DocumentServiceRestStub): - def __hash__(self): - return hash("GetDatasetSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.GetDatasetSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> dataset.DatasetSchema: - r"""Call the get dataset schema method over HTTP. - - Args: - request (~.document_service.GetDatasetSchemaRequest): - The request object. Request for ``GetDatasetSchema``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.dataset.DatasetSchema: - Dataset Schema. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/processors/*/dataset/datasetSchema}', - }, - ] - request, metadata = self._interceptor.pre_get_dataset_schema(request, metadata) - pb_request = document_service.GetDatasetSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = dataset.DatasetSchema() - pb_resp = dataset.DatasetSchema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_dataset_schema(resp) - return resp - - class _GetDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("GetDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "documentId" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.GetDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_service.GetDocumentResponse: - r"""Call the get document method over HTTP. - - Args: - request (~.document_service.GetDocumentRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_service.GetDocumentResponse: - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:getDocument', - }, - ] - request, metadata = self._interceptor.pre_get_document(request, metadata) - pb_request = document_service.GetDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_service.GetDocumentResponse() - pb_resp = document_service.GetDocumentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_document(resp) - return resp - - class _ImportDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ImportDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.ImportDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import documents method over HTTP. - - Args: - request (~.document_service.ImportDocumentsRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:importDocuments', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_documents(request, metadata) - pb_request = document_service.ImportDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_documents(resp) - return resp - - class _ListDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ListDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.ListDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_service.ListDocumentsResponse: - r"""Call the list documents method over HTTP. - - Args: - request (~.document_service.ListDocumentsRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_service.ListDocumentsResponse: - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:listDocuments', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_list_documents(request, metadata) - pb_request = document_service.ListDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_service.ListDocumentsResponse() - pb_resp = document_service.ListDocumentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_documents(resp) - return resp - - class _UpdateDataset(DocumentServiceRestStub): - def __hash__(self): - return hash("UpdateDataset") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.UpdateDatasetRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update dataset method over HTTP. - - Args: - request (~.document_service.UpdateDatasetRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta3/{dataset.name=projects/*/locations/*/processors/*/dataset}', - 'body': 'dataset', - }, - ] - request, metadata = self._interceptor.pre_update_dataset(request, metadata) - pb_request = document_service.UpdateDatasetRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_dataset(resp) - return resp - - class _UpdateDatasetSchema(DocumentServiceRestStub): - def __hash__(self): - return hash("UpdateDatasetSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.UpdateDatasetSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> dataset.DatasetSchema: - r"""Call the update dataset schema method over HTTP. - - Args: - request (~.document_service.UpdateDatasetSchemaRequest): - The request object. Request for ``UpdateDatasetSchema``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.dataset.DatasetSchema: - Dataset Schema. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta3/{dataset_schema.name=projects/*/locations/*/processors/*/dataset/datasetSchema}', - 'body': 'dataset_schema', - }, - ] - request, metadata = self._interceptor.pre_update_dataset_schema(request, metadata) - pb_request = document_service.UpdateDatasetSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = dataset.DatasetSchema() - pb_resp = dataset.DatasetSchema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_dataset_schema(resp) - return resp - - @property - def batch_delete_documents(self) -> Callable[ - [document_service.BatchDeleteDocumentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchDeleteDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_dataset_schema(self) -> Callable[ - [document_service.GetDatasetSchemaRequest], - dataset.DatasetSchema]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDatasetSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document_service.GetDocumentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_documents(self) -> Callable[ - [document_service.ImportDocumentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_dataset(self) -> Callable[ - [document_service.UpdateDatasetRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDataset(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_dataset_schema(self) -> Callable[ - [document_service.UpdateDatasetSchemaRequest], - dataset.DatasetSchema]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDatasetSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(DocumentServiceRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DocumentServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*}/locations', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta3/{name=projects/*/locations/*/operations}', - }, -{ - 'method': 'get', - 'uri': '/uiv1beta3/{name=projects/*/locations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py deleted file mode 100644 index 326a7114bf7d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/__init__.py +++ /dev/null @@ -1,242 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .dataset import ( - BatchDatasetDocuments, - Dataset, - DatasetSchema, - DocumentId, -) -from .document import ( - Document, - RevisionRef, -) -from .document_io import ( - BatchDocumentsInputConfig, - DocumentOutputConfig, - GcsDocument, - GcsDocuments, - GcsPrefix, - OcrConfig, - RawDocument, -) -from .document_processor_service import ( - BatchProcessMetadata, - BatchProcessRequest, - BatchProcessResponse, - CreateProcessorRequest, - DeleteProcessorMetadata, - DeleteProcessorRequest, - DeleteProcessorVersionMetadata, - DeleteProcessorVersionRequest, - DeployProcessorVersionMetadata, - DeployProcessorVersionRequest, - DeployProcessorVersionResponse, - DisableProcessorMetadata, - DisableProcessorRequest, - DisableProcessorResponse, - EnableProcessorMetadata, - EnableProcessorRequest, - EnableProcessorResponse, - EvaluateProcessorVersionMetadata, - EvaluateProcessorVersionRequest, - EvaluateProcessorVersionResponse, - FetchProcessorTypesRequest, - FetchProcessorTypesResponse, - GetEvaluationRequest, - GetProcessorRequest, - GetProcessorTypeRequest, - GetProcessorVersionRequest, - HumanReviewStatus, - ImportProcessorVersionMetadata, - ImportProcessorVersionRequest, - ImportProcessorVersionResponse, - ListEvaluationsRequest, - ListEvaluationsResponse, - ListProcessorsRequest, - ListProcessorsResponse, - ListProcessorTypesRequest, - ListProcessorTypesResponse, - ListProcessorVersionsRequest, - ListProcessorVersionsResponse, - ProcessOptions, - ProcessRequest, - ProcessResponse, - ReviewDocumentOperationMetadata, - ReviewDocumentRequest, - ReviewDocumentResponse, - SetDefaultProcessorVersionMetadata, - SetDefaultProcessorVersionRequest, - SetDefaultProcessorVersionResponse, - TrainProcessorVersionMetadata, - TrainProcessorVersionRequest, - TrainProcessorVersionResponse, - UndeployProcessorVersionMetadata, - UndeployProcessorVersionRequest, - UndeployProcessorVersionResponse, -) -from .document_schema import ( - DocumentSchema, - EntityTypeMetadata, - FieldExtractionMetadata, - PropertyMetadata, - SummaryOptions, -) -from .document_service import ( - BatchDeleteDocumentsMetadata, - BatchDeleteDocumentsRequest, - BatchDeleteDocumentsResponse, - DocumentMetadata, - DocumentPageRange, - GetDatasetSchemaRequest, - GetDocumentRequest, - GetDocumentResponse, - ImportDocumentsMetadata, - ImportDocumentsRequest, - ImportDocumentsResponse, - ListDocumentsRequest, - ListDocumentsResponse, - UpdateDatasetOperationMetadata, - UpdateDatasetRequest, - UpdateDatasetSchemaRequest, - DatasetSplitType, - DocumentLabelingState, -) -from .evaluation import ( - Evaluation, - EvaluationReference, -) -from .geometry import ( - BoundingPoly, - NormalizedVertex, - Vertex, -) -from .operation_metadata import ( - CommonOperationMetadata, -) -from .processor import ( - Processor, - ProcessorVersion, - ProcessorVersionAlias, -) -from .processor_type import ( - ProcessorType, -) - -__all__ = ( - 'Barcode', - 'BatchDatasetDocuments', - 'Dataset', - 'DatasetSchema', - 'DocumentId', - 'Document', - 'RevisionRef', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'OcrConfig', - 'RawDocument', - 'BatchProcessMetadata', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'CreateProcessorRequest', - 'DeleteProcessorMetadata', - 'DeleteProcessorRequest', - 'DeleteProcessorVersionMetadata', - 'DeleteProcessorVersionRequest', - 'DeployProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DisableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'EnableProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionResponse', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'GetEvaluationRequest', - 'GetProcessorRequest', - 'GetProcessorTypeRequest', - 'GetProcessorVersionRequest', - 'HumanReviewStatus', - 'ImportProcessorVersionMetadata', - 'ImportProcessorVersionRequest', - 'ImportProcessorVersionResponse', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'ProcessOptions', - 'ProcessRequest', - 'ProcessResponse', - 'ReviewDocumentOperationMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'SetDefaultProcessorVersionMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'DocumentSchema', - 'EntityTypeMetadata', - 'FieldExtractionMetadata', - 'PropertyMetadata', - 'SummaryOptions', - 'BatchDeleteDocumentsMetadata', - 'BatchDeleteDocumentsRequest', - 'BatchDeleteDocumentsResponse', - 'DocumentMetadata', - 'DocumentPageRange', - 'GetDatasetSchemaRequest', - 'GetDocumentRequest', - 'GetDocumentResponse', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDatasetOperationMetadata', - 'UpdateDatasetRequest', - 'UpdateDatasetSchemaRequest', - 'DatasetSplitType', - 'DocumentLabelingState', - 'Evaluation', - 'EvaluationReference', - 'BoundingPoly', - 'NormalizedVertex', - 'Vertex', - 'CommonOperationMetadata', - 'Processor', - 'ProcessorVersion', - 'ProcessorVersionAlias', - 'ProcessorType', -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py deleted file mode 100644 index adf4e74d6d0e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/barcode.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'Barcode', - }, -) - - -class Barcode(proto.Message): - r"""Encodes the detailed information of a barcode. - - Attributes: - format_ (str): - Format of a barcode. The supported formats are: - - - ``CODE_128``: Code 128 type. - - ``CODE_39``: Code 39 type. - - ``CODE_93``: Code 93 type. - - ``CODABAR``: Codabar type. - - ``DATA_MATRIX``: 2D Data Matrix type. - - ``ITF``: ITF type. - - ``EAN_13``: EAN-13 type. - - ``EAN_8``: EAN-8 type. - - ``QR_CODE``: 2D QR code type. - - ``UPC_A``: UPC-A type. - - ``UPC_E``: UPC-E type. - - ``PDF417``: PDF417 type. - - ``AZTEC``: 2D Aztec code type. - - ``DATABAR``: GS1 DataBar code type. - value_format (str): - Value format describes the format of the value that a - barcode encodes. The supported formats are: - - - ``CONTACT_INFO``: Contact information. - - ``EMAIL``: Email address. - - ``ISBN``: ISBN identifier. - - ``PHONE``: Phone number. - - ``PRODUCT``: Product. - - ``SMS``: SMS message. - - ``TEXT``: Text string. - - ``URL``: URL address. - - ``WIFI``: Wifi information. - - ``GEO``: Geo-localization. - - ``CALENDAR_EVENT``: Calendar event. - - ``DRIVER_LICENSE``: Driver's license. - raw_value (str): - Raw value encoded in the barcode. For example: - ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. - """ - - format_: str = proto.Field( - proto.STRING, - number=1, - ) - value_format: str = proto.Field( - proto.STRING, - number=2, - ) - raw_value: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/dataset.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/dataset.py deleted file mode 100644 index a07160a5ec8c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/dataset.py +++ /dev/null @@ -1,338 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -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_schema as gcd_document_schema - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'Dataset', - 'DocumentId', - 'DatasetSchema', - 'BatchDatasetDocuments', - }, -) - - -class Dataset(proto.Message): - r"""A singleton resource under a - [Processor][google.cloud.documentai.v1beta3.Processor] which - configures a collection of documents. - - 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_managed_config (google.cloud.documentai_v1beta3.types.Dataset.GCSManagedConfig): - Optional. User-managed Cloud Storage dataset - configuration. Use this configuration if the - dataset documents are stored under a - user-managed Cloud Storage location. - - This field is a member of `oneof`_ ``storage_source``. - document_warehouse_config (google.cloud.documentai_v1beta3.types.Dataset.DocumentWarehouseConfig): - Optional. Deprecated. Warehouse-based dataset - configuration is not supported. - - This field is a member of `oneof`_ ``storage_source``. - unmanaged_dataset_config (google.cloud.documentai_v1beta3.types.Dataset.UnmanagedDatasetConfig): - Optional. Unmanaged dataset configuration. - Use this configuration if the dataset documents - are managed by the document service internally - (not user-managed). - - This field is a member of `oneof`_ ``storage_source``. - spanner_indexing_config (google.cloud.documentai_v1beta3.types.Dataset.SpannerIndexingConfig): - Optional. A lightweight indexing source with - low latency and high reliability, but lacking - advanced features like CMEK and content-based - search. - - This field is a member of `oneof`_ ``indexing_source``. - name (str): - Dataset resource name. Format: - ``projects/{project}/locations/{location}/processors/{processor}/dataset`` - state (google.cloud.documentai_v1beta3.types.Dataset.State): - Required. State of the dataset. Ignored when - updating dataset. - """ - class State(proto.Enum): - r"""Different states of a dataset. - - Values: - STATE_UNSPECIFIED (0): - Default unspecified enum, should not be used. - UNINITIALIZED (1): - Dataset has not been initialized. - INITIALIZING (2): - Dataset is being initialized. - INITIALIZED (3): - Dataset has been initialized. - """ - STATE_UNSPECIFIED = 0 - UNINITIALIZED = 1 - INITIALIZING = 2 - INITIALIZED = 3 - - class GCSManagedConfig(proto.Message): - r"""Configuration specific to the Cloud Storage-based - implementation. - - Attributes: - gcs_prefix (google.cloud.documentai_v1beta3.types.GcsPrefix): - Required. The Cloud Storage URI (a directory) - where the documents belonging to the dataset - must be stored. - """ - - gcs_prefix: document_io.GcsPrefix = proto.Field( - proto.MESSAGE, - number=1, - message=document_io.GcsPrefix, - ) - - class DocumentWarehouseConfig(proto.Message): - r"""Configuration specific to the Document AI Warehouse-based - implementation. - - Attributes: - collection (str): - Output only. The collection in Document AI - Warehouse associated with the dataset. - schema (str): - Output only. The schema in Document AI - Warehouse associated with the dataset. - """ - - collection: str = proto.Field( - proto.STRING, - number=1, - ) - schema: str = proto.Field( - proto.STRING, - number=2, - ) - - class UnmanagedDatasetConfig(proto.Message): - r"""Configuration specific to an unmanaged dataset. - """ - - class SpannerIndexingConfig(proto.Message): - r"""Configuration specific to spanner-based indexing. - """ - - gcs_managed_config: GCSManagedConfig = proto.Field( - proto.MESSAGE, - number=3, - oneof='storage_source', - message=GCSManagedConfig, - ) - document_warehouse_config: DocumentWarehouseConfig = proto.Field( - proto.MESSAGE, - number=5, - oneof='storage_source', - message=DocumentWarehouseConfig, - ) - unmanaged_dataset_config: UnmanagedDatasetConfig = proto.Field( - proto.MESSAGE, - number=6, - oneof='storage_source', - message=UnmanagedDatasetConfig, - ) - spanner_indexing_config: SpannerIndexingConfig = proto.Field( - proto.MESSAGE, - number=4, - oneof='indexing_source', - message=SpannerIndexingConfig, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - - -class DocumentId(proto.Message): - r"""Document Identifier. - - 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_managed_doc_id (google.cloud.documentai_v1beta3.types.DocumentId.GCSManagedDocumentId): - A document id within user-managed Cloud - Storage. - - This field is a member of `oneof`_ ``type``. - unmanaged_doc_id (google.cloud.documentai_v1beta3.types.DocumentId.UnmanagedDocumentId): - A document id within unmanaged dataset. - - This field is a member of `oneof`_ ``type``. - revision_ref (google.cloud.documentai_v1beta3.types.RevisionRef): - Points to a specific revision of the document - if set. - """ - - class GCSManagedDocumentId(proto.Message): - r"""Identifies a document uniquely within the scope of a dataset - in the user-managed Cloud Storage option. - - Attributes: - gcs_uri (str): - Required. The Cloud Storage URI where the - actual document is stored. - cw_doc_id (str): - Id of the document (indexed) managed by - Content Warehouse. - """ - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - cw_doc_id: str = proto.Field( - proto.STRING, - number=2, - ) - - class UnmanagedDocumentId(proto.Message): - r"""Identifies a document uniquely within the scope of a dataset - in unmanaged option. - - Attributes: - doc_id (str): - Required. The id of the document. - """ - - doc_id: str = proto.Field( - proto.STRING, - number=1, - ) - - gcs_managed_doc_id: GCSManagedDocumentId = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=GCSManagedDocumentId, - ) - unmanaged_doc_id: UnmanagedDocumentId = proto.Field( - proto.MESSAGE, - number=4, - oneof='type', - message=UnmanagedDocumentId, - ) - revision_ref: document.RevisionRef = proto.Field( - proto.MESSAGE, - number=3, - message=document.RevisionRef, - ) - - -class DatasetSchema(proto.Message): - r"""Dataset Schema. - - Attributes: - name (str): - Dataset schema resource name. Format: - ``projects/{project}/locations/{location}/processors/{processor}/dataset/datasetSchema`` - document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): - Optional. Schema of the dataset. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=3, - message=gcd_document_schema.DocumentSchema, - ) - - -class BatchDatasetDocuments(proto.Message): - r"""Dataset documents that the batch operation will be applied - to. - - 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: - individual_document_ids (google.cloud.documentai_v1beta3.types.BatchDatasetDocuments.IndividualDocumentIds): - Document identifiers. - - This field is a member of `oneof`_ ``criteria``. - filter (str): - A filter matching the documents. Follows the same format and - restriction as - [google.cloud.documentai.master.ListDocumentsRequest.filter]. - - This field is a member of `oneof`_ ``criteria``. - """ - - class IndividualDocumentIds(proto.Message): - r"""List of individual DocumentIds. - - Attributes: - document_ids (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentId]): - Required. List of Document IDs indicating - where the actual documents are stored. - """ - - document_ids: MutableSequence['DocumentId'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DocumentId', - ) - - individual_document_ids: IndividualDocumentIds = proto.Field( - proto.MESSAGE, - number=1, - oneof='criteria', - message=IndividualDocumentIds, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - oneof='criteria', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document.py deleted file mode 100644 index cd699baefa50..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document.py +++ /dev/null @@ -1,1899 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1beta3.types import barcode as gcd_barcode -from google.cloud.documentai_v1beta3.types import geometry -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import color_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import money_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'Document', - 'RevisionRef', - }, -) - - -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. For more information, refer to `Google Cloud - Storage Request - URIs `__. - - 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 `media type (MIME - type) `__. - text (str): - Optional. UTF-8 encoded text in reading order - from the document. - text_styles (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Style]): - Styles for the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - pages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page]): - Visual page layout for the - [Document][google.cloud.documentai.v1beta3.Document]. - entities (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Entity]): - A list of entities detected on - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - For document shards, entities in this list may cross shard - boundaries. - entity_relations (MutableSequence[google.cloud.documentai_v1beta3.types.Document.EntityRelation]): - Placeholder. Relationship among - [Document.entities][google.cloud.documentai.v1beta3.Document.entities]. - text_changes (MutableSequence[google.cloud.documentai_v1beta3.types.Document.TextChange]): - Placeholder. A list of text corrections made to - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - This is usually used for annotating corrections to OCR - mistakes. Text changes for a given revision may not overlap - with each other. - shard_info (google.cloud.documentai_v1beta3.types.Document.ShardInfo): - Information about the sharding if this - document is sharded part of a larger document. - If the document is not sharded, this message is - not specified. - error (google.rpc.status_pb2.Status): - Any error that occurred while processing this - document. - revisions (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Revision]): - Placeholder. Revision history of this - document. - """ - - class ShardInfo(proto.Message): - r"""For a large document, sharding may be performed to produce - several document shards. Each document shard contains this field - to detail which shard it is. - - Attributes: - shard_index (int): - The 0-based index of this shard. - shard_count (int): - Total number of shards. - text_offset (int): - The index of the first character in - [Document.text][google.cloud.documentai.v1beta3.Document.text] - in the overall document global text. - """ - - shard_index: int = proto.Field( - proto.INT64, - number=1, - ) - shard_count: int = proto.Field( - proto.INT64, - number=2, - ) - text_offset: int = proto.Field( - proto.INT64, - number=3, - ) - - class Style(proto.Message): - r"""Annotation for common text style attributes. This adheres to - CSS conventions as much as possible. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - color (google.type.color_pb2.Color): - Text color. - background_color (google.type.color_pb2.Color): - Text background color. - font_weight (str): - `Font - weight `__. - Possible values are ``normal``, ``bold``, ``bolder``, and - ``lighter``. - text_style (str): - `Text - style `__. - Possible values are ``normal``, ``italic``, and ``oblique``. - text_decoration (str): - `Text - decoration `__. - Follows CSS standard. - font_size (google.cloud.documentai_v1beta3.types.Document.Style.FontSize): - Font size. - font_family (str): - Font family such as ``Arial``, ``Times New Roman``. - https://www.w3schools.com/cssref/pr_font_font-family.asp - """ - - class FontSize(proto.Message): - r"""Font size with unit. - - Attributes: - size (float): - Font size for the text. - unit (str): - Unit for the font size. Follows CSS naming (such as ``in``, - ``px``, and ``pt``). - """ - - size: float = proto.Field( - proto.FLOAT, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=2, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=3, - message=color_pb2.Color, - ) - font_weight: str = proto.Field( - proto.STRING, - number=4, - ) - text_style: str = proto.Field( - proto.STRING, - number=5, - ) - text_decoration: str = proto.Field( - proto.STRING, - number=6, - ) - font_size: 'Document.Style.FontSize' = proto.Field( - proto.MESSAGE, - number=7, - message='Document.Style.FontSize', - ) - font_family: str = proto.Field( - proto.STRING, - number=8, - ) - - class Page(proto.Message): - r"""A page in a [Document][google.cloud.documentai.v1beta3.Document]. - - Attributes: - page_number (int): - 1-based index for current - [Page][google.cloud.documentai.v1beta3.Document.Page] in a - parent [Document][google.cloud.documentai.v1beta3.Document]. - Useful when a page is taken out of a - [Document][google.cloud.documentai.v1beta3.Document] for - individual processing. - image (google.cloud.documentai_v1beta3.types.Document.Page.Image): - Rendered image for this page. This image is - preprocessed to remove any skew, rotation, and - distortions such that the annotation bounding - boxes can be upright and axis-aligned. - transforms (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Matrix]): - Transformation matrices that were applied to the original - document image to produce - [Page.image][google.cloud.documentai.v1beta3.Document.Page.image]. - dimension (google.cloud.documentai_v1beta3.types.Document.Page.Dimension): - Physical dimension of the page. - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for the page. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - blocks (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Block]): - A list of visually detected text blocks on - the page. A block has a set of lines (collected - into paragraphs) that have a common line-spacing - and orientation. - paragraphs (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Paragraph]): - A list of visually detected text paragraphs - on the page. A collection of lines that a human - would perceive as a paragraph. - lines (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Line]): - A list of visually detected text lines on the - page. A collection of tokens that a human would - perceive as a line. - tokens (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Token]): - A list of visually detected tokens on the - page. - visual_elements (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.VisualElement]): - A list of detected non-text visual elements - e.g. checkbox, signature etc. on the page. - tables (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table]): - A list of visually detected tables on the - page. - form_fields (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.FormField]): - A list of visually detected form fields on - the page. - symbols (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Symbol]): - A list of visually detected symbols on the - page. - detected_barcodes (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedBarcode]): - A list of detected barcodes. - image_quality_scores (google.cloud.documentai_v1beta3.types.Document.Page.ImageQualityScores): - Image quality scores. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this page. - """ - - class Dimension(proto.Message): - r"""Dimension for the page. - - Attributes: - width (float): - Page width. - height (float): - Page height. - unit (str): - Dimension unit. - """ - - width: float = proto.Field( - proto.FLOAT, - number=1, - ) - height: float = proto.Field( - proto.FLOAT, - number=2, - ) - unit: str = proto.Field( - proto.STRING, - number=3, - ) - - class Image(proto.Message): - r"""Rendered image contents for this page. - - Attributes: - content (bytes): - Raw byte content of the image. - mime_type (str): - Encoding `media type (MIME - type) `__ - for the image. - width (int): - Width of the image in pixels. - height (int): - Height of the image in pixels. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - width: int = proto.Field( - proto.INT32, - number=3, - ) - height: int = proto.Field( - proto.INT32, - number=4, - ) - - class Matrix(proto.Message): - r"""Representation for transformation matrix, intended to be - compatible and used with OpenCV format for image manipulation. - - Attributes: - rows (int): - Number of rows in the matrix. - cols (int): - Number of columns in the matrix. - type_ (int): - This encodes information about what data type the matrix - uses. For example, 0 (CV_8U) is an unsigned 8-bit image. For - the full list of OpenCV primitive data types, please refer - to - https://docs.opencv.org/4.3.0/d1/d1b/group__core__hal__interface.html - data (bytes): - The matrix data. - """ - - rows: int = proto.Field( - proto.INT32, - number=1, - ) - cols: int = proto.Field( - proto.INT32, - number=2, - ) - type_: int = proto.Field( - proto.INT32, - number=3, - ) - data: bytes = proto.Field( - proto.BYTES, - number=4, - ) - - class Layout(proto.Message): - r"""Visual element describing a layout unit on a page. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - confidence (float): - Confidence of the current - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - within context of the object this layout is for. e.g. - confidence can be for a single token, a table, a visual - element, etc. depending on context. Range ``[0, 1]``. - bounding_poly (google.cloud.documentai_v1beta3.types.BoundingPoly): - The bounding polygon for the - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout]. - orientation (google.cloud.documentai_v1beta3.types.Document.Page.Layout.Orientation): - Detected orientation for the - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout]. - """ - class Orientation(proto.Enum): - r"""Detected human reading orientation. - - Values: - ORIENTATION_UNSPECIFIED (0): - Unspecified orientation. - PAGE_UP (1): - Orientation is aligned with page up. - PAGE_RIGHT (2): - Orientation is aligned with page right. - Turn the head 90 degrees clockwise from upright - to read. - PAGE_DOWN (3): - Orientation is aligned with page down. - Turn the head 180 degrees from upright to read. - PAGE_LEFT (4): - Orientation is aligned with page left. - Turn the head 90 degrees counterclockwise from - upright to read. - """ - ORIENTATION_UNSPECIFIED = 0 - PAGE_UP = 1 - PAGE_RIGHT = 2 - PAGE_DOWN = 3 - PAGE_LEFT = 4 - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=3, - message=geometry.BoundingPoly, - ) - orientation: 'Document.Page.Layout.Orientation' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Page.Layout.Orientation', - ) - - class Block(proto.Message): - r"""A block has a set of lines (collected into paragraphs) that - have a common line-spacing and orientation. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Block][google.cloud.documentai.v1beta3.Document.Page.Block]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Paragraph(proto.Message): - r"""A collection of lines that a human would perceive as a - paragraph. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Paragraph][google.cloud.documentai.v1beta3.Document.Page.Paragraph]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Line(proto.Message): - r"""A collection of tokens that a human would perceive as a line. - Does not cross column boundaries, can be horizontal, vertical, - etc. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Line][google.cloud.documentai.v1beta3.Document.Page.Line]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this annotation. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - class Token(proto.Message): - r"""A detected token. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. - detected_break (google.cloud.documentai_v1beta3.types.Document.Page.Token.DetectedBreak): - Detected break at the end of a - [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this annotation. - style_info (google.cloud.documentai_v1beta3.types.Document.Page.Token.StyleInfo): - Text style attributes. - """ - - class DetectedBreak(proto.Message): - r"""Detected break at the end of a - [Token][google.cloud.documentai.v1beta3.Document.Page.Token]. - - Attributes: - type_ (google.cloud.documentai_v1beta3.types.Document.Page.Token.DetectedBreak.Type): - Detected break type. - """ - class Type(proto.Enum): - r"""Enum to denote the type of break found. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified break type. - SPACE (1): - A single whitespace. - WIDE_SPACE (2): - A wider whitespace. - HYPHEN (3): - A hyphen that indicates that a token has been - split across lines. - """ - TYPE_UNSPECIFIED = 0 - SPACE = 1 - WIDE_SPACE = 2 - HYPHEN = 3 - - type_: 'Document.Page.Token.DetectedBreak.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Document.Page.Token.DetectedBreak.Type', - ) - - class StyleInfo(proto.Message): - r"""Font and other text style attributes. - - Attributes: - font_size (int): - Font size in points (``1`` point is ``¹⁄₇₂`` inches). - pixel_font_size (float): - Font size in pixels, equal to *unrounded - [font_size][google.cloud.documentai.v1beta3.Document.Page.Token.StyleInfo.font_size]* - - - *resolution* ÷ ``72.0``. - letter_spacing (float): - Letter spacing in points. - font_type (str): - Name or style of the font. - bold (bool): - Whether the text is bold (equivalent to - [font_weight][google.cloud.documentai.v1beta3.Document.Page.Token.StyleInfo.font_weight] - is at least ``700``). - italic (bool): - Whether the text is italic. - underlined (bool): - Whether the text is underlined. - strikeout (bool): - Whether the text is strikethrough. - subscript (bool): - Whether the text is a subscript. - superscript (bool): - Whether the text is a superscript. - smallcaps (bool): - Whether the text is in small caps. - font_weight (int): - TrueType weight on a scale ``100`` (thin) to ``1000`` - (ultra-heavy). Normal is ``400``, bold is ``700``. - handwritten (bool): - Whether the text is handwritten. - text_color (google.type.color_pb2.Color): - Color of the text. - background_color (google.type.color_pb2.Color): - Color of the background. - """ - - font_size: int = proto.Field( - proto.INT32, - number=1, - ) - pixel_font_size: float = proto.Field( - proto.DOUBLE, - number=2, - ) - letter_spacing: float = proto.Field( - proto.DOUBLE, - number=3, - ) - font_type: str = proto.Field( - proto.STRING, - number=4, - ) - bold: bool = proto.Field( - proto.BOOL, - number=5, - ) - italic: bool = proto.Field( - proto.BOOL, - number=6, - ) - underlined: bool = proto.Field( - proto.BOOL, - number=7, - ) - strikeout: bool = proto.Field( - proto.BOOL, - number=8, - ) - subscript: bool = proto.Field( - proto.BOOL, - number=9, - ) - superscript: bool = proto.Field( - proto.BOOL, - number=10, - ) - smallcaps: bool = proto.Field( - proto.BOOL, - number=11, - ) - font_weight: int = proto.Field( - proto.INT32, - number=12, - ) - handwritten: bool = proto.Field( - proto.BOOL, - number=13, - ) - text_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=14, - message=color_pb2.Color, - ) - background_color: color_pb2.Color = proto.Field( - proto.MESSAGE, - number=15, - message=color_pb2.Color, - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_break: 'Document.Page.Token.DetectedBreak' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Token.DetectedBreak', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=4, - message='Document.Provenance', - ) - style_info: 'Document.Page.Token.StyleInfo' = proto.Field( - proto.MESSAGE, - number=5, - message='Document.Page.Token.StyleInfo', - ) - - class Symbol(proto.Message): - r"""A detected symbol. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Symbol][google.cloud.documentai.v1beta3.Document.Page.Symbol]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.DetectedLanguage', - ) - - class VisualElement(proto.Message): - r"""Detected non-text visual elements e.g. checkbox, signature - etc. on the page. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [VisualElement][google.cloud.documentai.v1beta3.Document.Page.VisualElement]. - type_ (str): - Type of the - [VisualElement][google.cloud.documentai.v1beta3.Document.Page.VisualElement]. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - - class Table(proto.Message): - r"""A table representation similar to HTML table structure. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [Table][google.cloud.documentai.v1beta3.Document.Page.Table]. - header_rows (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): - Header rows of the table. - body_rows (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableRow]): - Body rows of the table. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this table. - """ - - class TableRow(proto.Message): - r"""A row of table cells. - - Attributes: - cells (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.Table.TableCell]): - Cells that make up this row. - """ - - cells: MutableSequence['Document.Page.Table.TableCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.Page.Table.TableCell', - ) - - class TableCell(proto.Message): - r"""A cell representation inside the table. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [TableCell][google.cloud.documentai.v1beta3.Document.Page.Table.TableCell]. - row_span (int): - How many rows this cell spans. - col_span (int): - How many columns this cell spans. - detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages together with - confidence. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - row_span: int = proto.Field( - proto.INT32, - number=2, - ) - col_span: int = proto.Field( - proto.INT32, - number=3, - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - header_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.Table.TableRow', - ) - body_rows: MutableSequence['Document.Page.Table.TableRow'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.Table.TableRow', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=5, - message='Document.Provenance', - ) - - class FormField(proto.Message): - r"""A form field detected on the page. - - Attributes: - field_name (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta3.Document.Page.FormField] - name. e.g. ``Address``, ``Email``, ``Grand total``, - ``Phone number``, etc. - field_value (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for the - [FormField][google.cloud.documentai.v1beta3.Document.Page.FormField] - value. - name_detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages for name - together with confidence. - value_detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): - A list of detected languages for value - together with confidence. - value_type (str): - If the value is non-textual, this field represents the type. - Current valid values are: - - - blank (this indicates the ``field_value`` is normal text) - - ``unfilled_checkbox`` - - ``filled_checkbox`` - corrected_key_text (str): - Created for Labeling UI to export key text. If corrections - were made to the text identified by the - ``field_name.text_anchor``, this field will contain the - correction. - corrected_value_text (str): - Created for Labeling UI to export value text. If corrections - were made to the text identified by the - ``field_value.text_anchor``, this field will contain the - correction. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this annotation. - """ - - field_name: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - field_value: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Layout', - ) - name_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Page.DetectedLanguage', - ) - value_detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - value_type: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_key_text: str = proto.Field( - proto.STRING, - number=6, - ) - corrected_value_text: str = proto.Field( - proto.STRING, - number=7, - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=8, - message='Document.Provenance', - ) - - class DetectedBarcode(proto.Message): - r"""A detected barcode. - - Attributes: - layout (google.cloud.documentai_v1beta3.types.Document.Page.Layout): - [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] - for - [DetectedBarcode][google.cloud.documentai.v1beta3.Document.Page.DetectedBarcode]. - barcode (google.cloud.documentai_v1beta3.types.Barcode): - Detailed barcode information of the - [DetectedBarcode][google.cloud.documentai.v1beta3.Document.Page.DetectedBarcode]. - """ - - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.Page.Layout', - ) - barcode: gcd_barcode.Barcode = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_barcode.Barcode, - ) - - class DetectedLanguage(proto.Message): - r"""Detected language for a structural component. - - Attributes: - language_code (str): - The `BCP-47 language - code `__, - such as ``en-US`` or ``sr-Latn``. - confidence (float): - Confidence of detected language. Range ``[0, 1]``. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - class ImageQualityScores(proto.Message): - r"""Image quality scores for the page image. - - Attributes: - quality_score (float): - The overall quality score. Range ``[0, 1]`` where ``1`` is - perfect quality. - detected_defects (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.ImageQualityScores.DetectedDefect]): - A list of detected defects. - """ - - class DetectedDefect(proto.Message): - r"""Image Quality Defects - - Attributes: - type_ (str): - Name of the defect type. Supported values are: - - - ``quality/defect_blurry`` - - ``quality/defect_noisy`` - - ``quality/defect_dark`` - - ``quality/defect_faint`` - - ``quality/defect_text_too_small`` - - ``quality/defect_document_cutoff`` - - ``quality/defect_text_cutoff`` - - ``quality/defect_glare`` - confidence (float): - Confidence of detected defect. Range ``[0, 1]`` where ``1`` - indicates strong confidence that the defect exists. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - quality_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - detected_defects: MutableSequence['Document.Page.ImageQualityScores.DetectedDefect'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Document.Page.ImageQualityScores.DetectedDefect', - ) - - page_number: int = proto.Field( - proto.INT32, - number=1, - ) - image: 'Document.Page.Image' = proto.Field( - proto.MESSAGE, - number=13, - message='Document.Page.Image', - ) - transforms: MutableSequence['Document.Page.Matrix'] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='Document.Page.Matrix', - ) - dimension: 'Document.Page.Dimension' = proto.Field( - proto.MESSAGE, - number=2, - message='Document.Page.Dimension', - ) - layout: 'Document.Page.Layout' = proto.Field( - proto.MESSAGE, - number=3, - message='Document.Page.Layout', - ) - detected_languages: MutableSequence['Document.Page.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Document.Page.DetectedLanguage', - ) - blocks: MutableSequence['Document.Page.Block'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Document.Page.Block', - ) - paragraphs: MutableSequence['Document.Page.Paragraph'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Document.Page.Paragraph', - ) - lines: MutableSequence['Document.Page.Line'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Document.Page.Line', - ) - tokens: MutableSequence['Document.Page.Token'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='Document.Page.Token', - ) - visual_elements: MutableSequence['Document.Page.VisualElement'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Document.Page.VisualElement', - ) - tables: MutableSequence['Document.Page.Table'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Page.Table', - ) - form_fields: MutableSequence['Document.Page.FormField'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='Document.Page.FormField', - ) - symbols: MutableSequence['Document.Page.Symbol'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='Document.Page.Symbol', - ) - detected_barcodes: MutableSequence['Document.Page.DetectedBarcode'] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message='Document.Page.DetectedBarcode', - ) - image_quality_scores: 'Document.Page.ImageQualityScores' = proto.Field( - proto.MESSAGE, - number=17, - message='Document.Page.ImageQualityScores', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=16, - message='Document.Provenance', - ) - - class Entity(proto.Message): - r"""An entity that could be a phrase in the text or a property - that belongs to the document. It is a known entity type, such as - a person, an organization, or location. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Optional. Provenance of the entity. Text anchor indexing - into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - type_ (str): - Required. Entity type from a schema e.g. ``Address``. - mention_text (str): - Optional. Text value of the entity e.g. - ``1600 Amphitheatre Pkwy``. - mention_id (str): - Optional. Deprecated. Use ``id`` field instead. - confidence (float): - Optional. Confidence of detected Schema entity. Range - ``[0, 1]``. - page_anchor (google.cloud.documentai_v1beta3.types.Document.PageAnchor): - Optional. Represents the provenance of this - entity wrt. the location on the page where it - was found. - id (str): - Optional. Canonical id. This will be a unique - value in the entity list for this document. - normalized_value (google.cloud.documentai_v1beta3.types.Document.Entity.NormalizedValue): - Optional. Normalized entity value. Absent if - the extracted value could not be converted or - the type (e.g. address) is not supported for - certain parsers. This field is also only - populated for certain supported document types. - properties (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Entity]): - Optional. Entities can be nested to form a - hierarchical data structure representing the - content in the document. - provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - Optional. The history of this annotation. - redacted (bool): - Optional. Whether the entity will be redacted - for de-identification purposes. - """ - - class NormalizedValue(proto.Message): - r"""Parsed and normalized entity value. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - money_value (google.type.money_pb2.Money): - Money value. See also: - - https://github.com/googleapis/googleapis/blob/master/google/type/money.proto - - This field is a member of `oneof`_ ``structured_value``. - date_value (google.type.date_pb2.Date): - Date value. Includes year, month, day. See - also: - https://github.com/googleapis/googleapis/blob/master/google/type/date.proto - - This field is a member of `oneof`_ ``structured_value``. - datetime_value (google.type.datetime_pb2.DateTime): - DateTime value. Includes date, time, and - timezone. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/datetime.proto - - This field is a member of `oneof`_ ``structured_value``. - address_value (google.type.postal_address_pb2.PostalAddress): - Postal address. See also: - https://github.com/googleapis/googleapis/blob/master/google/type/postal_address.proto - - This field is a member of `oneof`_ ``structured_value``. - boolean_value (bool): - Boolean value. Can be used for entities with - binary values, or for checkboxes. - - This field is a member of `oneof`_ ``structured_value``. - integer_value (int): - Integer value. - - This field is a member of `oneof`_ ``structured_value``. - float_value (float): - Float value. - - This field is a member of `oneof`_ ``structured_value``. - text (str): - Optional. An optional field to store a normalized string. - For some entity types, one of respective - ``structured_value`` fields may also be populated. Also not - all the types of ``structured_value`` will be normalized. - For example, some processors may not generate ``float`` or - ``integer`` normalized text by default. - - Below are sample formats mapped to structured values. - - - Money/Currency type (``money_value``) is in the ISO 4217 - text format. - - Date type (``date_value``) is in the ISO 8601 text - format. - - Datetime type (``datetime_value``) is in the ISO 8601 - text format. - """ - - money_value: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - oneof='structured_value', - message=money_pb2.Money, - ) - date_value: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - oneof='structured_value', - message=date_pb2.Date, - ) - datetime_value: datetime_pb2.DateTime = proto.Field( - proto.MESSAGE, - number=4, - oneof='structured_value', - message=datetime_pb2.DateTime, - ) - address_value: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=5, - oneof='structured_value', - message=postal_address_pb2.PostalAddress, - ) - boolean_value: bool = proto.Field( - proto.BOOL, - number=6, - oneof='structured_value', - ) - integer_value: int = proto.Field( - proto.INT32, - number=7, - oneof='structured_value', - ) - float_value: float = proto.Field( - proto.FLOAT, - number=8, - oneof='structured_value', - ) - text: str = proto.Field( - proto.STRING, - number=1, - ) - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - mention_text: str = proto.Field( - proto.STRING, - number=3, - ) - mention_id: str = proto.Field( - proto.STRING, - number=4, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - page_anchor: 'Document.PageAnchor' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.PageAnchor', - ) - id: str = proto.Field( - proto.STRING, - number=7, - ) - normalized_value: 'Document.Entity.NormalizedValue' = proto.Field( - proto.MESSAGE, - number=9, - message='Document.Entity.NormalizedValue', - ) - properties: MutableSequence['Document.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Document.Entity', - ) - provenance: 'Document.Provenance' = proto.Field( - proto.MESSAGE, - number=11, - message='Document.Provenance', - ) - redacted: bool = proto.Field( - proto.BOOL, - number=12, - ) - - class EntityRelation(proto.Message): - r"""Relationship between - [Entities][google.cloud.documentai.v1beta3.Document.Entity]. - - Attributes: - subject_id (str): - Subject entity id. - object_id (str): - Object entity id. - relation (str): - Relationship description. - """ - - subject_id: str = proto.Field( - proto.STRING, - number=1, - ) - object_id: str = proto.Field( - proto.STRING, - number=2, - ) - relation: str = proto.Field( - proto.STRING, - number=3, - ) - - class TextAnchor(proto.Message): - r"""Text reference indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - - Attributes: - text_segments (MutableSequence[google.cloud.documentai_v1beta3.types.Document.TextAnchor.TextSegment]): - The text segments from the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - content (str): - Contains the content of the text span so that users do not - have to look it up in the text_segments. It is always - populated for formFields. - """ - - class TextSegment(proto.Message): - r"""A text segment in the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. The - indices may be out of bounds which indicate that the text extends - into another document shard for large sharded documents. See - [ShardInfo.text_offset][google.cloud.documentai.v1beta3.Document.ShardInfo.text_offset] - - Attributes: - start_index (int): - [TextSegment][google.cloud.documentai.v1beta3.Document.TextAnchor.TextSegment] - start UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - end_index (int): - [TextSegment][google.cloud.documentai.v1beta3.Document.TextAnchor.TextSegment] - half open end UTF-8 char index in the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - """ - - start_index: int = proto.Field( - proto.INT64, - number=1, - ) - end_index: int = proto.Field( - proto.INT64, - number=2, - ) - - text_segments: MutableSequence['Document.TextAnchor.TextSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.TextAnchor.TextSegment', - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class PageAnchor(proto.Message): - r"""Referencing the visual context of the entity in the - [Document.pages][google.cloud.documentai.v1beta3.Document.pages]. - Page anchors can be cross-page, consist of multiple bounding - polygons and optionally reference specific layout element types. - - Attributes: - page_refs (MutableSequence[google.cloud.documentai_v1beta3.types.Document.PageAnchor.PageRef]): - One or more references to visual page - elements - """ - - class PageRef(proto.Message): - r"""Represents a weak reference to a page element within a - document. - - Attributes: - page (int): - Required. Index into the - [Document.pages][google.cloud.documentai.v1beta3.Document.pages] - element, for example using - ``[Document.pages][page_refs.page]`` to locate the related - page element. This field is skipped when its value is the - default ``0``. See - https://developers.google.com/protocol-buffers/docs/proto3#json. - layout_type (google.cloud.documentai_v1beta3.types.Document.PageAnchor.PageRef.LayoutType): - Optional. The type of the layout element that - is being referenced if any. - layout_id (str): - Optional. Deprecated. Use - [PageRef.bounding_poly][google.cloud.documentai.v1beta3.Document.PageAnchor.PageRef.bounding_poly] - instead. - bounding_poly (google.cloud.documentai_v1beta3.types.BoundingPoly): - Optional. Identifies the bounding polygon of a layout - element on the page. If ``layout_type`` is set, the bounding - polygon must be exactly the same to the layout element it's - referring to. - confidence (float): - Optional. Confidence of detected page element, if - applicable. Range ``[0, 1]``. - """ - class LayoutType(proto.Enum): - r"""The type of layout that is being referenced. - - Values: - LAYOUT_TYPE_UNSPECIFIED (0): - Layout Unspecified. - BLOCK (1): - References a - [Page.blocks][google.cloud.documentai.v1beta3.Document.Page.blocks] - element. - PARAGRAPH (2): - References a - [Page.paragraphs][google.cloud.documentai.v1beta3.Document.Page.paragraphs] - element. - LINE (3): - References a - [Page.lines][google.cloud.documentai.v1beta3.Document.Page.lines] - element. - TOKEN (4): - References a - [Page.tokens][google.cloud.documentai.v1beta3.Document.Page.tokens] - element. - VISUAL_ELEMENT (5): - References a - [Page.visual_elements][google.cloud.documentai.v1beta3.Document.Page.visual_elements] - element. - TABLE (6): - Refrrences a - [Page.tables][google.cloud.documentai.v1beta3.Document.Page.tables] - element. - FORM_FIELD (7): - References a - [Page.form_fields][google.cloud.documentai.v1beta3.Document.Page.form_fields] - element. - """ - LAYOUT_TYPE_UNSPECIFIED = 0 - BLOCK = 1 - PARAGRAPH = 2 - LINE = 3 - TOKEN = 4 - VISUAL_ELEMENT = 5 - TABLE = 6 - FORM_FIELD = 7 - - page: int = proto.Field( - proto.INT64, - number=1, - ) - layout_type: 'Document.PageAnchor.PageRef.LayoutType' = proto.Field( - proto.ENUM, - number=2, - enum='Document.PageAnchor.PageRef.LayoutType', - ) - layout_id: str = proto.Field( - proto.STRING, - number=3, - ) - bounding_poly: geometry.BoundingPoly = proto.Field( - proto.MESSAGE, - number=4, - message=geometry.BoundingPoly, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - - page_refs: MutableSequence['Document.PageAnchor.PageRef'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document.PageAnchor.PageRef', - ) - - class Provenance(proto.Message): - r"""Structure to identify provenance relationships between - annotations in different revisions. - - Attributes: - revision (int): - The index of the revision that produced this - element. - id (int): - The Id of this operation. Needs to be unique - within the scope of the revision. - parents (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Provenance.Parent]): - References to the original elements that are - replaced. - type_ (google.cloud.documentai_v1beta3.types.Document.Provenance.OperationType): - The type of provenance operation. - """ - class OperationType(proto.Enum): - r"""If a processor or agent does an explicit operation on - existing elements. - - Values: - OPERATION_TYPE_UNSPECIFIED (0): - Operation type unspecified. If no operation is specified a - provenance entry is simply used to match against a - ``parent``. - ADD (1): - Add an element. - REMOVE (2): - Remove an element identified by ``parent``. - UPDATE (7): - Updates any fields within the given - provenance scope of the message. It overwrites - the fields rather than replacing them. Use this - when you want to update a field value of an - entity without also updating all the child - properties. - REPLACE (3): - Currently unused. Replace an element identified by - ``parent``. - EVAL_REQUESTED (4): - Deprecated. Request human review for the element identified - by ``parent``. - EVAL_APPROVED (5): - Deprecated. Element is reviewed and approved - at human review, confidence will be set to 1.0. - EVAL_SKIPPED (6): - Deprecated. Element is skipped in the - validation process. - """ - OPERATION_TYPE_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - UPDATE = 7 - REPLACE = 3 - EVAL_REQUESTED = 4 - EVAL_APPROVED = 5 - EVAL_SKIPPED = 6 - - class Parent(proto.Message): - r"""The parent element the current element is based on. Used for - referencing/aligning, removal and replacement operations. - - Attributes: - revision (int): - The index of the index into current revision's parent_ids - list. - index (int): - The index of the parent item in the - corresponding item list (eg. list of entities, - properties within entities, etc.) in the parent - revision. - id (int): - The id of the parent provenance. - """ - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - index: int = proto.Field( - proto.INT32, - number=3, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - - revision: int = proto.Field( - proto.INT32, - number=1, - ) - id: int = proto.Field( - proto.INT32, - number=2, - ) - parents: MutableSequence['Document.Provenance.Parent'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance.Parent', - ) - type_: 'Document.Provenance.OperationType' = proto.Field( - proto.ENUM, - number=4, - enum='Document.Provenance.OperationType', - ) - - class Revision(proto.Message): - r"""Contains past or forward revisions of this document. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - agent (str): - If the change was made by a person specify - the name or id of that person. - - This field is a member of `oneof`_ ``source``. - processor (str): - If the annotation was made by processor - identify the processor by its resource name. - - This field is a member of `oneof`_ ``source``. - id (str): - Id of the revision, internally generated by - doc proto storage. Unique within the context of - the document. - parent (MutableSequence[int]): - The revisions that this revision is based on. This can - include one or more parent (when documents are merged.) This - field represents the index into the ``revisions`` field. - parent_ids (MutableSequence[str]): - The revisions that this revision is based on. Must include - all the ids that have anything to do with this revision - - eg. there are ``provenance.parent.revision`` fields that - index into this field. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the revision was created, - internally generated by doc proto storage at the - time of create. - human_review (google.cloud.documentai_v1beta3.types.Document.Revision.HumanReview): - Human Review information of this revision. - """ - - class HumanReview(proto.Message): - r"""Human Review information of the document. - - Attributes: - state (str): - Human review state. e.g. ``requested``, ``succeeded``, - ``rejected``. - state_message (str): - A message providing more details about the current state of - processing. For example, the rejection reason when the state - is ``rejected``. - """ - - state: str = proto.Field( - proto.STRING, - number=1, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - - agent: str = proto.Field( - proto.STRING, - number=4, - oneof='source', - ) - processor: str = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - id: str = proto.Field( - proto.STRING, - number=1, - ) - parent: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=2, - ) - parent_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - human_review: 'Document.Revision.HumanReview' = proto.Field( - proto.MESSAGE, - number=6, - message='Document.Revision.HumanReview', - ) - - class TextChange(proto.Message): - r"""This message is used for text changes aka. OCR corrections. - - Attributes: - text_anchor (google.cloud.documentai_v1beta3.types.Document.TextAnchor): - Provenance of the correction. Text anchor indexing into the - [Document.text][google.cloud.documentai.v1beta3.Document.text]. - There can only be a single ``TextAnchor.text_segments`` - element. If the start and end index of the text segment are - the same, the text change is inserted before that index. - changed_text (str): - The text that replaces the text identified in the - ``text_anchor``. - provenance (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Provenance]): - The history of this annotation. - """ - - text_anchor: 'Document.TextAnchor' = proto.Field( - proto.MESSAGE, - number=1, - message='Document.TextAnchor', - ) - changed_text: str = proto.Field( - proto.STRING, - number=2, - ) - provenance: MutableSequence['Document.Provenance'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Document.Provenance', - ) - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='source', - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - text: str = proto.Field( - proto.STRING, - number=4, - ) - text_styles: MutableSequence[Style] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Style, - ) - pages: MutableSequence[Page] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Page, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Entity, - ) - entity_relations: MutableSequence[EntityRelation] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=EntityRelation, - ) - text_changes: MutableSequence[TextChange] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=TextChange, - ) - shard_info: ShardInfo = proto.Field( - proto.MESSAGE, - number=9, - message=ShardInfo, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - revisions: MutableSequence[Revision] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Revision, - ) - - -class RevisionRef(proto.Message): - r"""The revision reference specifies which revision on the - document to read. - - 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: - revision_case (google.cloud.documentai_v1beta3.types.RevisionRef.RevisionCase): - Reads the revision by the predefined case. - - This field is a member of `oneof`_ ``source``. - revision_id (str): - Reads the revision given by the id. - - This field is a member of `oneof`_ ``source``. - latest_processor_version (str): - Reads the revision generated by the processor version. The - format takes the full resource name of processor version. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - - This field is a member of `oneof`_ ``source``. - """ - class RevisionCase(proto.Enum): - r"""Some predefined revision cases. - - Values: - REVISION_CASE_UNSPECIFIED (0): - Unspecified case, fall back to read the - ``LATEST_HUMAN_REVIEW``. - LATEST_HUMAN_REVIEW (1): - The latest revision made by a human. - LATEST_TIMESTAMP (2): - The latest revision based on timestamp. - BASE_OCR_REVISION (3): - The first (OCR) revision. - """ - REVISION_CASE_UNSPECIFIED = 0 - LATEST_HUMAN_REVIEW = 1 - LATEST_TIMESTAMP = 2 - BASE_OCR_REVISION = 3 - - revision_case: RevisionCase = proto.Field( - proto.ENUM, - number=1, - oneof='source', - enum=RevisionCase, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - latest_processor_version: str = proto.Field( - proto.STRING, - number=3, - oneof='source', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py deleted file mode 100644 index 9ff4a7ce15fc..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_io.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'RawDocument', - 'GcsDocument', - 'GcsDocuments', - 'GcsPrefix', - 'BatchDocumentsInputConfig', - 'DocumentOutputConfig', - 'OcrConfig', - }, -) - - -class RawDocument(proto.Message): - r"""Payload message of raw document content (bytes). - - Attributes: - content (bytes): - Inline document content. - mime_type (str): - An IANA MIME type (RFC6838) indicating the nature and format - of the - [content][google.cloud.documentai.v1beta3.RawDocument.content]. - display_name (str): - The display name of the document, it supports all Unicode - characters except the following: ``*``, ``?``, ``[``, ``]``, - ``%``, ``{``, ``}``,\ ``'``, ``\"``, ``,`` ``~``, ``=`` and - ``:`` are reserved. If not specified, a default ID is - generated. - """ - - content: bytes = proto.Field( - proto.BYTES, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GcsDocument(proto.Message): - r"""Specifies a document stored on Cloud Storage. - - Attributes: - gcs_uri (str): - The Cloud Storage object uri. - mime_type (str): - An IANA MIME type (RFC6838) of the content. - """ - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GcsDocuments(proto.Message): - r"""Specifies a set of documents on Cloud Storage. - - Attributes: - documents (MutableSequence[google.cloud.documentai_v1beta3.types.GcsDocument]): - The list of documents. - """ - - documents: MutableSequence['GcsDocument'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GcsDocument', - ) - - -class GcsPrefix(proto.Message): - r"""Specifies all documents on Cloud Storage with a common - prefix. - - Attributes: - gcs_uri_prefix (str): - The URI prefix. - """ - - gcs_uri_prefix: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchDocumentsInputConfig(proto.Message): - r"""The common config to specify a set of documents used as - input. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (google.cloud.documentai_v1beta3.types.GcsPrefix): - The set of documents that match the specified Cloud Storage - ``gcs_prefix``. - - This field is a member of `oneof`_ ``source``. - gcs_documents (google.cloud.documentai_v1beta3.types.GcsDocuments): - The set of documents individually specified - on Cloud Storage. - - This field is a member of `oneof`_ ``source``. - """ - - gcs_prefix: 'GcsPrefix' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsPrefix', - ) - gcs_documents: 'GcsDocuments' = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsDocuments', - ) - - -class DocumentOutputConfig(proto.Message): - r"""Config that controls the output of documents. All documents - will be written as a JSON file. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_output_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig.GcsOutputConfig): - Output config to write the results to Cloud - Storage. - - This field is a member of `oneof`_ ``destination``. - """ - - class GcsOutputConfig(proto.Message): - r"""The configuration used when outputting documents. - - Attributes: - gcs_uri (str): - The Cloud Storage uri (a directory) of the - output. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies which fields to include in the output documents. - Only supports top level document and pages field so it must - be in the form of ``{document_field_name}`` or - ``pages.{page_field_name}``. - sharding_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig.GcsOutputConfig.ShardingConfig): - Specifies the sharding config for the output - document. - """ - - class ShardingConfig(proto.Message): - r"""The sharding config for the output document. - - Attributes: - pages_per_shard (int): - The number of pages per shard. - pages_overlap (int): - The number of overlapping pages between - consecutive shards. - """ - - pages_per_shard: int = proto.Field( - proto.INT32, - number=1, - ) - pages_overlap: int = proto.Field( - proto.INT32, - number=2, - ) - - gcs_uri: str = proto.Field( - proto.STRING, - number=1, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - sharding_config: 'DocumentOutputConfig.GcsOutputConfig.ShardingConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='DocumentOutputConfig.GcsOutputConfig.ShardingConfig', - ) - - gcs_output_config: GcsOutputConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message=GcsOutputConfig, - ) - - -class OcrConfig(proto.Message): - r"""Config for Document OCR. - - Attributes: - hints (google.cloud.documentai_v1beta3.types.OcrConfig.Hints): - Hints for the OCR model. - enable_native_pdf_parsing (bool): - Enables special handling for PDFs with - existing text information. Results in better - text extraction quality in such PDF inputs. - enable_image_quality_scores (bool): - Enables intelligent document quality scores - after OCR. Can help with diagnosing why OCR - responses are of poor quality for a given input. - Adds additional latency comparable to regular - OCR to the process call. - advanced_ocr_options (MutableSequence[str]): - A list of advanced OCR options to further fine-tune OCR - behavior. Current valid values are: - - - ``legacy_layout``: a heuristics layout detection - algorithm, which serves as an alternative to the current - ML-based layout detection algorithm. Customers can choose - the best suitable layout algorithm based on their - situation. - enable_symbol (bool): - Includes symbol level OCR information if set - to true. - compute_style_info (bool): - Turn on font identification model and return font style - information. Deprecated, use - [PremiumFeatures.compute_style_info][google.cloud.documentai.v1beta3.OcrConfig.PremiumFeatures.compute_style_info] - instead. - disable_character_boxes_detection (bool): - Turn off character box detector in OCR - engine. Character box detection is enabled by - default in OCR 2.0 (and later) processors. - premium_features (google.cloud.documentai_v1beta3.types.OcrConfig.PremiumFeatures): - Configurations for premium OCR features. - """ - - class Hints(proto.Message): - r"""Hints for OCR Engine - - Attributes: - language_hints (MutableSequence[str]): - List of BCP-47 language codes to use for OCR. - In most cases, not specifying it yields the best - results since it enables automatic language - detection. For languages based on the Latin - alphabet, setting 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). - """ - - language_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class PremiumFeatures(proto.Message): - r"""Configurations for premium OCR features. - - Attributes: - enable_selection_mark_detection (bool): - Turn on selection mark detector in OCR - engine. Only available in OCR 2.0 (and later) - processors. - compute_style_info (bool): - Turn on font identification model and return - font style information. - enable_math_ocr (bool): - Turn on the model that can extract LaTeX math - formulas. - """ - - enable_selection_mark_detection: bool = proto.Field( - proto.BOOL, - number=3, - ) - compute_style_info: bool = proto.Field( - proto.BOOL, - number=4, - ) - enable_math_ocr: bool = proto.Field( - proto.BOOL, - number=5, - ) - - hints: Hints = proto.Field( - proto.MESSAGE, - number=2, - message=Hints, - ) - enable_native_pdf_parsing: bool = proto.Field( - proto.BOOL, - number=3, - ) - enable_image_quality_scores: bool = proto.Field( - proto.BOOL, - number=4, - ) - advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - enable_symbol: bool = proto.Field( - proto.BOOL, - number=6, - ) - compute_style_info: bool = proto.Field( - proto.BOOL, - number=8, - ) - disable_character_boxes_detection: bool = proto.Field( - proto.BOOL, - number=10, - ) - premium_features: PremiumFeatures = proto.Field( - proto.MESSAGE, - number=11, - message=PremiumFeatures, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py deleted file mode 100644 index 83e5eb0656ac..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_processor_service.py +++ /dev/null @@ -1,1936 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1beta3.types import document as gcd_document -from google.cloud.documentai_v1beta3.types import document_io -from google.cloud.documentai_v1beta3.types import document_schema as gcd_document_schema -from google.cloud.documentai_v1beta3.types import evaluation as gcd_evaluation -from google.cloud.documentai_v1beta3.types import operation_metadata -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'ProcessOptions', - 'ProcessRequest', - 'HumanReviewStatus', - 'ProcessResponse', - 'BatchProcessRequest', - 'BatchProcessResponse', - 'BatchProcessMetadata', - 'FetchProcessorTypesRequest', - 'FetchProcessorTypesResponse', - 'ListProcessorTypesRequest', - 'ListProcessorTypesResponse', - 'ListProcessorsRequest', - 'ListProcessorsResponse', - 'GetProcessorTypeRequest', - 'GetProcessorRequest', - 'GetProcessorVersionRequest', - 'ListProcessorVersionsRequest', - 'ListProcessorVersionsResponse', - 'DeleteProcessorVersionRequest', - 'DeleteProcessorVersionMetadata', - 'DeployProcessorVersionRequest', - 'DeployProcessorVersionResponse', - 'DeployProcessorVersionMetadata', - 'UndeployProcessorVersionRequest', - 'UndeployProcessorVersionResponse', - 'UndeployProcessorVersionMetadata', - 'CreateProcessorRequest', - 'DeleteProcessorRequest', - 'DeleteProcessorMetadata', - 'EnableProcessorRequest', - 'EnableProcessorResponse', - 'EnableProcessorMetadata', - 'DisableProcessorRequest', - 'DisableProcessorResponse', - 'DisableProcessorMetadata', - 'SetDefaultProcessorVersionRequest', - 'SetDefaultProcessorVersionResponse', - 'SetDefaultProcessorVersionMetadata', - 'TrainProcessorVersionRequest', - 'TrainProcessorVersionResponse', - 'TrainProcessorVersionMetadata', - 'ReviewDocumentRequest', - 'ReviewDocumentResponse', - 'ReviewDocumentOperationMetadata', - 'EvaluateProcessorVersionRequest', - 'EvaluateProcessorVersionMetadata', - 'EvaluateProcessorVersionResponse', - 'GetEvaluationRequest', - 'ListEvaluationsRequest', - 'ListEvaluationsResponse', - 'ImportProcessorVersionRequest', - 'ImportProcessorVersionResponse', - 'ImportProcessorVersionMetadata', - }, -) - - -class ProcessOptions(proto.Message): - r"""Options for Process API - - 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: - individual_page_selector (google.cloud.documentai_v1beta3.types.ProcessOptions.IndividualPageSelector): - Which pages to process (1-indexed). - - This field is a member of `oneof`_ ``page_range``. - from_start (int): - Only process certain pages from the start. - Process all if the document has fewer pages. - - This field is a member of `oneof`_ ``page_range``. - from_end (int): - Only process certain pages from the end, same - as above. - - This field is a member of `oneof`_ ``page_range``. - ocr_config (google.cloud.documentai_v1beta3.types.OcrConfig): - Only applicable to ``OCR_PROCESSOR`` and - ``FORM_PARSER_PROCESSOR``. Returns error if set on other - processor types. - schema_override (google.cloud.documentai_v1beta3.types.DocumentSchema): - Optional. Override the schema of the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - Will return an Invalid Argument error if this field is set - when the underlying - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - doesn't support schema override. - """ - - class IndividualPageSelector(proto.Message): - r"""A list of individual page numbers. - - Attributes: - pages (MutableSequence[int]): - Optional. Indices of the pages (starting from - 1). - """ - - pages: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=1, - ) - - individual_page_selector: IndividualPageSelector = proto.Field( - proto.MESSAGE, - number=5, - oneof='page_range', - message=IndividualPageSelector, - ) - from_start: int = proto.Field( - proto.INT32, - number=6, - oneof='page_range', - ) - from_end: int = proto.Field( - proto.INT32, - number=7, - oneof='page_range', - ) - ocr_config: document_io.OcrConfig = proto.Field( - proto.MESSAGE, - number=1, - message=document_io.OcrConfig, - ) - schema_override: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=8, - message=gcd_document_schema.DocumentSchema, - ) - - -class ProcessRequest(proto.Message): - r"""Request message for the - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - 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``. - gcs_document (google.cloud.documentai_v1beta3.types.GcsDocument): - A raw document on Google Cloud Storage. - - 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][google.cloud.documentai.v1beta3.Document.content] - and - [mime_type][google.cloud.documentai.v1beta3.Document.mime_type] - fields must be set. - skip_human_review (bool): - Whether human review should be skipped for this request. - Default to ``false``. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies which fields to include in the - [ProcessResponse.document][google.cloud.documentai.v1beta3.ProcessResponse.document] - output. Only supports top-level document and pages field, so - it must be in the form of ``{document_field_name}`` or - ``pages.{page_field_name}``. - process_options (google.cloud.documentai_v1beta3.types.ProcessOptions): - Inference-time options for the process API - labels (MutableMapping[str, str]): - Optional. The labels with user-defined - metadata for the request. - Label keys and values can be no longer than 63 - characters (Unicode codepoints) and can only - contain lowercase letters, numeric characters, - underscores, and dashes. International - characters are allowed. Label values are - optional. Label keys must start with a letter. - """ - - inline_document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - raw_document: document_io.RawDocument = proto.Field( - proto.MESSAGE, - number=5, - oneof='source', - message=document_io.RawDocument, - ) - gcs_document: document_io.GcsDocument = proto.Field( - proto.MESSAGE, - number=8, - oneof='source', - message=document_io.GcsDocument, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=3, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=6, - message=field_mask_pb2.FieldMask, - ) - process_options: 'ProcessOptions' = proto.Field( - proto.MESSAGE, - number=7, - message='ProcessOptions', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - - -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][google.cloud.documentai.v1beta3.HumanReviewStatus.state] - is ``HUMAN_REVIEW_IN_PROGRESS``. It has the same response - type and metadata as the long-running operation returned by - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument]. - """ - class State(proto.Enum): - r"""The final state of human review on a processed document. - - Values: - STATE_UNSPECIFIED (0): - Human review state is unspecified. Most - likely due to an internal error. - SKIPPED (1): - Human review is skipped for the document. - This can happen because human review isn't - enabled on the processor or the processing - request has been set to skip this document. - VALIDATION_PASSED (2): - Human review validation is triggered and - passed, so no review is needed. - IN_PROGRESS (3): - Human review validation is triggered and the - document is under review. - ERROR (4): - Some error happened during triggering human review, see the - [state_message][google.cloud.documentai.v1beta3.HumanReviewStatus.state_message] - for details. - """ - STATE_UNSPECIFIED = 0 - SKIPPED = 1 - VALIDATION_PASSED = 2 - IN_PROGRESS = 3 - ERROR = 4 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ProcessResponse(proto.Message): - r"""Response message for the - [ProcessDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument] - 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 isn't triggered, this - field is empty. It has the same response type and metadata - as the long-running operation returned by - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument]. - human_review_status (google.cloud.documentai_v1beta3.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=2, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='HumanReviewStatus', - ) - - -class BatchProcessRequest(proto.Message): - r"""Request message for - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - Attributes: - name (str): - Required. The resource name of - [Processor][google.cloud.documentai.v1beta3.Processor] or - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - Format: - ``projects/{project}/locations/{location}/processors/{processor}``, - or - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - input_configs (MutableSequence[google.cloud.documentai_v1beta3.types.BatchProcessRequest.BatchInputConfig]): - The input config for each single document in - the batch process. - output_config (google.cloud.documentai_v1beta3.types.BatchProcessRequest.BatchOutputConfig): - The overall output config for batch process. - input_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): - The input documents for the - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments] - method. - document_output_config (google.cloud.documentai_v1beta3.types.DocumentOutputConfig): - The output configuration for the - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments] - method. - skip_human_review (bool): - Whether human review should be skipped for this request. - Default to ``false``. - process_options (google.cloud.documentai_v1beta3.types.ProcessOptions): - Inference-time options for the process API - labels (MutableMapping[str, str]): - Optional. The labels with user-defined - metadata for the request. - Label keys and values can be no longer than 63 - characters (Unicode codepoints) and can only - contain lowercase letters, numeric characters, - underscores, and dashes. International - characters are allowed. Label values are - optional. Label keys must start with a letter. - """ - - 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): - An IANA published `media type (MIME - type) `__ - of the input. If the input is a raw document, refer to - `supported file - types `__ - for the list of media types. If the input is a - [Document][google.cloud.documentai.v1beta3.Document], the - type should be ``application/json``. - """ - - gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - mime_type: str = proto.Field( - proto.STRING, - number=2, - ) - - class BatchOutputConfig(proto.Message): - r"""The output configuration in the - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments] - method. - - Attributes: - gcs_destination (str): - The output Cloud Storage directory to put the - processed documents. - """ - - gcs_destination: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - input_configs: MutableSequence[BatchInputConfig] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=BatchInputConfig, - ) - output_config: BatchOutputConfig = proto.Field( - proto.MESSAGE, - number=3, - message=BatchOutputConfig, - ) - input_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=5, - message=document_io.BatchDocumentsInputConfig, - ) - document_output_config: document_io.DocumentOutputConfig = proto.Field( - proto.MESSAGE, - number=6, - message=document_io.DocumentOutputConfig, - ) - skip_human_review: bool = proto.Field( - proto.BOOL, - number=4, - ) - process_options: 'ProcessOptions' = proto.Field( - proto.MESSAGE, - number=7, - message='ProcessOptions', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - - -class BatchProcessResponse(proto.Message): - r"""Response message for - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - """ - - -class BatchProcessMetadata(proto.Message): - r"""The long-running operation metadata for - [BatchProcessDocuments][google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments]. - - Attributes: - state (google.cloud.documentai_v1beta3.types.BatchProcessMetadata.State): - The state of the current batch processing. - state_message (str): - A message providing more details about the - current state of processing. For example, the - error message if the operation is failed. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - individual_process_statuses (MutableSequence[google.cloud.documentai_v1beta3.types.BatchProcessMetadata.IndividualProcessStatus]): - The list of response details of each - document. - """ - class State(proto.Enum): - r"""Possible states of the batch processing operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - WAITING (1): - Request operation is waiting for scheduling. - RUNNING (2): - Request is being processed. - SUCCEEDED (3): - The batch processing completed successfully. - CANCELLING (4): - The batch processing was being cancelled. - CANCELLED (5): - The batch processing was cancelled. - FAILED (6): - The batch processing has failed. - """ - STATE_UNSPECIFIED = 0 - WAITING = 1 - RUNNING = 2 - SUCCEEDED = 3 - CANCELLING = 4 - CANCELLED = 5 - FAILED = 6 - - class IndividualProcessStatus(proto.Message): - r"""The status of a each individual document in the batch - process. - - Attributes: - input_gcs_source (str): - The source of the document, same as the - [input_gcs_source][google.cloud.documentai.v1beta3.BatchProcessMetadata.IndividualProcessStatus.input_gcs_source] - field in the request when the batch process started. - status (google.rpc.status_pb2.Status): - The status processing the document. - output_gcs_destination (str): - The Cloud Storage output destination (in the request as - [DocumentOutputConfig.GcsOutputConfig.gcs_uri][google.cloud.documentai.v1beta3.DocumentOutputConfig.GcsOutputConfig.gcs_uri]) - 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 isn't triggered, this - field will be empty. It has the same response type and - metadata as the long-running operation returned by the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - method. - human_review_status (google.cloud.documentai_v1beta3.types.HumanReviewStatus): - The status of human review on the processed - document. - """ - - input_gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - output_gcs_destination: str = proto.Field( - proto.STRING, - number=3, - ) - human_review_operation: str = proto.Field( - proto.STRING, - number=4, - ) - human_review_status: 'HumanReviewStatus' = proto.Field( - proto.MESSAGE, - number=5, - message='HumanReviewStatus', - ) - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - individual_process_statuses: MutableSequence[IndividualProcessStatus] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=IndividualProcessStatus, - ) - - -class FetchProcessorTypesRequest(proto.Message): - r"""Request message for the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. Some processor types may require the project be added to an - allowlist. - - Attributes: - parent (str): - Required. The location of processor types to list. Format: - ``projects/{project}/locations/{location}``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FetchProcessorTypesResponse(proto.Message): - r"""Response message for the - [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes] - method. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType]): - The list of processor types. - """ - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - - -class ListProcessorTypesRequest(proto.Message): - r"""Request message for the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. Some processor types may require the project be added to an - allowlist. - - Attributes: - parent (str): - Required. The location of processor types to list. Format: - ``projects/{project}/locations/{location}``. - page_size (int): - The maximum number of processor types to return. If - unspecified, at most ``100`` processor types will be - returned. The maximum value is ``500``. Values above ``500`` - will be coerced to ``500``. - page_token (str): - Used to retrieve the next page of results, - empty if at the end of the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListProcessorTypesResponse(proto.Message): - r"""Response message for the - [ListProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes] - method. - - Attributes: - processor_types (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType]): - The processor types. - next_page_token (str): - Points to the next page, otherwise empty. - """ - - @property - def raw_page(self): - return self - - processor_types: MutableSequence[processor_type.ProcessorType] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=processor_type.ProcessorType, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListProcessorsRequest(proto.Message): - r"""Request message for list all processors belongs to a project. - - Attributes: - parent (str): - Required. The parent (project and location) which owns this - collection of Processors. Format: - ``projects/{project}/locations/{location}`` - page_size (int): - The maximum number of processors to return. If unspecified, - at most ``50`` processors will be returned. The maximum - value is ``100``. Values above ``100`` will be coerced to - ``100``. - page_token (str): - We will return the processors sorted by - creation time. The page token will point to the - next processor. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListProcessorsResponse(proto.Message): - r"""Response message for the - [ListProcessors][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors] - method. - - Attributes: - processors (MutableSequence[google.cloud.documentai_v1beta3.types.Processor]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processors: MutableSequence[gcd_processor.Processor] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.Processor, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetProcessorTypeRequest(proto.Message): - r"""Request message for the - [GetProcessorType][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType] - method. - - Attributes: - name (str): - Required. The processor type resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorRequest(proto.Message): - r"""Request message for the - [GetProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetProcessorVersionRequest(proto.Message): - r"""Request message for the - [GetProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProcessorVersionsRequest(proto.Message): - r"""Request message for list all processor versions belongs to a - processor. - - Attributes: - parent (str): - Required. The parent (project, location and processor) to - list all versions. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - page_size (int): - The maximum number of processor versions to return. If - unspecified, at most ``10`` processor versions will be - returned. The maximum value is ``20``. Values above ``20`` - will be coerced to ``20``. - page_token (str): - We will return the processor versions sorted - by creation time. The page token will point to - the next processor version. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListProcessorVersionsResponse(proto.Message): - r"""Response message for the - [ListProcessorVersions][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions] - method. - - Attributes: - processor_versions (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorVersion]): - The list of processors. - next_page_token (str): - Points to the next processor, otherwise - empty. - """ - - @property - def raw_page(self): - return self - - processor_versions: MutableSequence[gcd_processor.ProcessorVersion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_processor.ProcessorVersion, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteProcessorVersionRequest(proto.Message): - r"""Request message for the - [DeleteProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor version resource name - to be deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [DeleteProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class DeployProcessorVersionRequest(proto.Message): - r"""Request message for the - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor version resource name - to be deployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeployProcessorVersionResponse(proto.Message): - r"""Response message for the - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - method. - - """ - - -class DeployProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [DeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class UndeployProcessorVersionRequest(proto.Message): - r"""Request message for the - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - method. - - Attributes: - name (str): - Required. The processor version resource name - to be undeployed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeployProcessorVersionResponse(proto.Message): - r"""Response message for the - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - method. - - """ - - -class UndeployProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [UndeployProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class CreateProcessorRequest(proto.Message): - r"""Request message for the - [CreateProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor] - method. Notice this request is sent to a regionalized backend - service. If the - [ProcessorType][google.cloud.documentai.v1beta3.ProcessorType] isn't - available in that region, the creation fails. - - 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][google.cloud.documentai.v1beta3.Processor.type] - and - [Processor.display_name][google.cloud.documentai.v1beta3.Processor.display_name] - to be set. Also, the - [Processor.kms_key_name][google.cloud.documentai.v1beta3.Processor.kms_key_name] - field must be set if the processor is under CMEK. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - processor: gcd_processor.Processor = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_processor.Processor, - ) - - -class DeleteProcessorRequest(proto.Message): - r"""Request message for the - [DeleteProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name to be - deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProcessorMetadata(proto.Message): - r"""The long-running operation metadata for the - [DeleteProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class EnableProcessorRequest(proto.Message): - r"""Request message for the - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name to be - enabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EnableProcessorResponse(proto.Message): - r"""Response message for the - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - method. Intentionally empty proto for adding fields in future. - - """ - - -class EnableProcessorMetadata(proto.Message): - r"""The long-running operation metadata for the - [EnableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class DisableProcessorRequest(proto.Message): - r"""Request message for the - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - method. - - Attributes: - name (str): - Required. The processor resource name to be - disabled. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DisableProcessorResponse(proto.Message): - r"""Response message for the - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - method. Intentionally empty proto for adding fields in future. - - """ - - -class DisableProcessorMetadata(proto.Message): - r"""The long-running operation metadata for the - [DisableProcessor][google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - - -class SetDefaultProcessorVersionRequest(proto.Message): - r"""Request message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - method. - - Attributes: - processor (str): - Required. The resource name of the - [Processor][google.cloud.documentai.v1beta3.Processor] to - change default version. - default_processor_version (str): - Required. The resource name of child - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to use as default. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{version}`` - """ - - processor: str = proto.Field( - proto.STRING, - number=1, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SetDefaultProcessorVersionResponse(proto.Message): - r"""Response message for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - method. - - """ - - -class SetDefaultProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [SetDefaultProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class TrainProcessorVersionRequest(proto.Message): - r"""Request message for the - [TrainProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion] - 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: - custom_document_extraction_options (google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest.CustomDocumentExtractionOptions): - Options to control Custom Document Extraction - (CDE) Processor. - - This field is a member of `oneof`_ ``processor_flags``. - foundation_model_tuning_options (google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest.FoundationModelTuningOptions): - Options to control foundation model tuning of - a processor. - - This field is a member of `oneof`_ ``processor_flags``. - parent (str): - Required. The parent (project, location and processor) to - create the new version for. Format: - ``projects/{project}/locations/{location}/processors/{processor}``. - processor_version (google.cloud.documentai_v1beta3.types.ProcessorVersion): - Required. The processor version to be - created. - document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): - Optional. The schema the processor version - will be trained with. - input_data (google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest.InputData): - Optional. The input data used to train the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - base_processor_version (str): - Optional. The processor version to use as a base for - training. This processor version must be a child of - ``parent``. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}``. - """ - - class InputData(proto.Message): - r"""The input data used to train a new - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - - Attributes: - training_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): - The documents used for training the new - version. - test_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): - The documents used for testing the trained - version. - """ - - training_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=3, - message=document_io.BatchDocumentsInputConfig, - ) - test_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=4, - message=document_io.BatchDocumentsInputConfig, - ) - - class CustomDocumentExtractionOptions(proto.Message): - r"""Options to control the training of the Custom Document - Extraction (CDE) Processor. - - Attributes: - training_method (google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest.CustomDocumentExtractionOptions.TrainingMethod): - Training method to use for CDE training. - """ - class TrainingMethod(proto.Enum): - r"""Training Method for CDE. ``TRAINING_METHOD_UNSPECIFIED`` will fall - back to ``MODEL_BASED``. - - Values: - TRAINING_METHOD_UNSPECIFIED (0): - No description available. - MODEL_BASED (1): - No description available. - TEMPLATE_BASED (2): - No description available. - """ - TRAINING_METHOD_UNSPECIFIED = 0 - MODEL_BASED = 1 - TEMPLATE_BASED = 2 - - training_method: 'TrainProcessorVersionRequest.CustomDocumentExtractionOptions.TrainingMethod' = proto.Field( - proto.ENUM, - number=3, - enum='TrainProcessorVersionRequest.CustomDocumentExtractionOptions.TrainingMethod', - ) - - class FoundationModelTuningOptions(proto.Message): - r"""Options to control foundation model tuning of the processor. - - Attributes: - train_steps (int): - Optional. The number of steps to run for - model tuning. Valid values are between 1 and - 400. If not provided, recommended steps will be - used. - learning_rate_multiplier (float): - Optional. The multiplier to apply to the - recommended learning rate. Valid values are - between 0.1 and 10. If not provided, recommended - learning rate will be used. - """ - - train_steps: int = proto.Field( - proto.INT32, - number=2, - ) - learning_rate_multiplier: float = proto.Field( - proto.FLOAT, - number=3, - ) - - custom_document_extraction_options: CustomDocumentExtractionOptions = proto.Field( - proto.MESSAGE, - number=5, - oneof='processor_flags', - message=CustomDocumentExtractionOptions, - ) - foundation_model_tuning_options: FoundationModelTuningOptions = proto.Field( - proto.MESSAGE, - number=12, - oneof='processor_flags', - message=FoundationModelTuningOptions, - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - processor_version: gcd_processor.ProcessorVersion = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_processor.ProcessorVersion, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=10, - message=gcd_document_schema.DocumentSchema, - ) - input_data: InputData = proto.Field( - proto.MESSAGE, - number=4, - message=InputData, - ) - base_processor_version: str = proto.Field( - proto.STRING, - number=8, - ) - - -class TrainProcessorVersionResponse(proto.Message): - r"""The response for - [TrainProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion]. - - Attributes: - processor_version (str): - The resource name of the processor version - produced by training. - """ - - processor_version: str = proto.Field( - proto.STRING, - number=1, - ) - - -class TrainProcessorVersionMetadata(proto.Message): - r"""The metadata that represents a processor version being - created. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - training_dataset_validation (google.cloud.documentai_v1beta3.types.TrainProcessorVersionMetadata.DatasetValidation): - The training dataset validation information. - test_dataset_validation (google.cloud.documentai_v1beta3.types.TrainProcessorVersionMetadata.DatasetValidation): - The test dataset validation information. - """ - - class DatasetValidation(proto.Message): - r"""The dataset validation information. - This includes any and all errors with documents and the dataset. - - Attributes: - document_error_count (int): - The total number of document errors. - dataset_error_count (int): - The total number of dataset errors. - document_errors (MutableSequence[google.rpc.status_pb2.Status]): - Error information pertaining to specific - documents. A maximum of 10 document errors will - be returned. Any document with errors will not - be used throughout training. - dataset_errors (MutableSequence[google.rpc.status_pb2.Status]): - Error information for the dataset as a whole. - A maximum of 10 dataset errors will be returned. - A single dataset error is terminal for training. - """ - - document_error_count: int = proto.Field( - proto.INT32, - number=3, - ) - dataset_error_count: int = proto.Field( - proto.INT32, - number=4, - ) - document_errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - dataset_errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - training_dataset_validation: DatasetValidation = proto.Field( - proto.MESSAGE, - number=2, - message=DatasetValidation, - ) - test_dataset_validation: DatasetValidation = proto.Field( - proto.MESSAGE, - number=3, - message=DatasetValidation, - ) - - -class ReviewDocumentRequest(proto.Message): - r"""Request message for the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - 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][google.cloud.documentai.v1beta3.HumanReviewConfig] - that the document will be reviewed with. - document (google.cloud.documentai_v1beta3.types.Document): - The document that needs human review. - enable_schema_validation (bool): - Whether the validation should be performed on - the ad-hoc review request. - priority (google.cloud.documentai_v1beta3.types.ReviewDocumentRequest.Priority): - The priority of the human review task. - document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): - The document schema of the human review task. - """ - class Priority(proto.Enum): - r"""The priority level of the human review task. - - Values: - DEFAULT (0): - The default priority level. - URGENT (1): - The urgent priority level. The labeling - manager should allocate labeler resource to the - urgent task queue to respect this priority - level. - """ - DEFAULT = 0 - URGENT = 1 - - inline_document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message=gcd_document.Document, - ) - human_review_config: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - enable_schema_validation: bool = proto.Field( - proto.BOOL, - number=3, - ) - priority: Priority = proto.Field( - proto.ENUM, - number=5, - enum=Priority, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_document_schema.DocumentSchema, - ) - - -class ReviewDocumentResponse(proto.Message): - r"""Response message for the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - method. - - Attributes: - gcs_destination (str): - The Cloud Storage uri for the human reviewed - document if the review is succeeded. - state (google.cloud.documentai_v1beta3.types.ReviewDocumentResponse.State): - The state of the review operation. - rejection_reason (str): - The reason why the review is rejected by - reviewer. - """ - class State(proto.Enum): - r"""Possible states of the review operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - REJECTED (1): - The review operation is rejected by the - reviewer. - SUCCEEDED (2): - The review operation is succeeded. - """ - STATE_UNSPECIFIED = 0 - REJECTED = 1 - SUCCEEDED = 2 - - gcs_destination: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - rejection_reason: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ReviewDocumentOperationMetadata(proto.Message): - r"""The long-running operation metadata for the - [ReviewDocument][google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument] - 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 long-running operation. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - RUNNING (1): - Operation is still running. - CANCELLING (2): - Operation is being cancelled. - SUCCEEDED (3): - Operation succeeded. - FAILED (4): - Operation failed. - CANCELLED (5): - Operation is cancelled. - """ - STATE_UNSPECIFIED = 0 - RUNNING = 1 - CANCELLING = 2 - SUCCEEDED = 3 - FAILED = 4 - CANCELLED = 5 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=operation_metadata.CommonOperationMetadata, - ) - question_id: str = proto.Field( - proto.STRING, - number=6, - ) - - -class EvaluateProcessorVersionRequest(proto.Message): - r"""Evaluates the given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - against the supplied documents. - - Attributes: - processor_version (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to evaluate. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - evaluation_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): - Optional. The documents used in the - evaluation. If unspecified, use the processor's - dataset as evaluation input. - """ - - processor_version: str = proto.Field( - proto.STRING, - number=1, - ) - evaluation_documents: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=3, - message=document_io.BatchDocumentsInputConfig, - ) - - -class EvaluateProcessorVersionMetadata(proto.Message): - r"""Metadata of the - [EvaluateProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class EvaluateProcessorVersionResponse(proto.Message): - r"""Response of the - [EvaluateProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion] - method. - - Attributes: - evaluation (str): - The resource name of the created evaluation. - """ - - evaluation: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEvaluationRequest(proto.Message): - r"""Retrieves a specific Evaluation. - - Attributes: - name (str): - Required. The resource name of the - [Evaluation][google.cloud.documentai.v1beta3.Evaluation] to - get. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEvaluationsRequest(proto.Message): - r"""Retrieves a list of evaluations for a given - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion]. - - Attributes: - parent (str): - Required. The resource name of the - [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] - to list evaluations for. - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - page_size (int): - The standard list page size. If unspecified, at most ``5`` - evaluations are returned. The maximum value is ``100``. - Values above ``100`` are coerced to ``100``. - page_token (str): - A page token, received from a previous ``ListEvaluations`` - call. Provide this to retrieve the subsequent page. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEvaluationsResponse(proto.Message): - r"""The response from ``ListEvaluations``. - - Attributes: - evaluations (MutableSequence[google.cloud.documentai_v1beta3.types.Evaluation]): - The evaluations requested. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - evaluations: MutableSequence[gcd_evaluation.Evaluation] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_evaluation.Evaluation, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ImportProcessorVersionRequest(proto.Message): - r"""The request message for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - The Document AI `Service - Agent `__ of the - destination project must have `Document AI Editor - role `__ - on the source project. - - The destination project is specified as part of the - [parent][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.parent] - field. The source project is specified as part of the - [source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.processor_version_source] - or - [external_processor_version_source][google.cloud.documentai.v1beta3.ImportProcessorVersionRequest.external_processor_version_source] - field. - - 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: - processor_version_source (str): - The source processor version to import from. The source - processor version and destination processor need to be in - the same environment and region. Note that ProcessorVersions - with ``model_type`` ``MODEL_TYPE_LLM`` are not supported. - - This field is a member of `oneof`_ ``source``. - external_processor_version_source (google.cloud.documentai_v1beta3.types.ImportProcessorVersionRequest.ExternalProcessorVersionSource): - The source processor version to import from. - It can be from a different environment and - region than the destination processor. - - This field is a member of `oneof`_ ``source``. - parent (str): - Required. The destination processor name to create the - processor version in. Format: - ``projects/{project}/locations/{location}/processors/{processor}`` - """ - - class ExternalProcessorVersionSource(proto.Message): - r"""The external source processor version. - - Attributes: - processor_version (str): - Required. The processor version name. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` - service_endpoint (str): - Optional. The Document AI service endpoint. - For example, - 'https://us-documentai.googleapis.com' - """ - - processor_version: str = proto.Field( - proto.STRING, - number=1, - ) - service_endpoint: str = proto.Field( - proto.STRING, - number=2, - ) - - processor_version_source: str = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - external_processor_version_source: ExternalProcessorVersionSource = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message=ExternalProcessorVersionSource, - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ImportProcessorVersionResponse(proto.Message): - r"""The response message for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - Attributes: - processor_version (str): - The destination processor version name. - """ - - processor_version: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ImportProcessorVersionMetadata(proto.Message): - r"""The long-running operation metadata for the - [ImportProcessorVersion][google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion] - method. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata for the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py deleted file mode 100644 index 64327085681b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_schema.py +++ /dev/null @@ -1,383 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'SummaryOptions', - 'FieldExtractionMetadata', - 'PropertyMetadata', - 'EntityTypeMetadata', - 'DocumentSchema', - }, -) - - -class SummaryOptions(proto.Message): - r"""Metadata for document summarization. - - Attributes: - length (google.cloud.documentai_v1beta3.types.SummaryOptions.Length): - How long the summary should be. - format_ (google.cloud.documentai_v1beta3.types.SummaryOptions.Format): - The format the summary should be in. - """ - class Length(proto.Enum): - r"""The Length enum. - - Values: - LENGTH_UNSPECIFIED (0): - Default. - BRIEF (1): - A brief summary of one or two sentences. - MODERATE (2): - A paragraph-length summary. - COMPREHENSIVE (3): - The longest option available. - """ - LENGTH_UNSPECIFIED = 0 - BRIEF = 1 - MODERATE = 2 - COMPREHENSIVE = 3 - - class Format(proto.Enum): - r"""The Format enum. - - Values: - FORMAT_UNSPECIFIED (0): - Default. - PARAGRAPH (1): - Format the output in paragraphs. - BULLETS (2): - Format the output in bullets. - """ - FORMAT_UNSPECIFIED = 0 - PARAGRAPH = 1 - BULLETS = 2 - - length: Length = proto.Field( - proto.ENUM, - number=1, - enum=Length, - ) - format_: Format = proto.Field( - proto.ENUM, - number=2, - enum=Format, - ) - - -class FieldExtractionMetadata(proto.Message): - r"""Metadata for how this field value is extracted. - - Attributes: - summary_options (google.cloud.documentai_v1beta3.types.SummaryOptions): - Summary options config. - """ - - summary_options: 'SummaryOptions' = proto.Field( - proto.MESSAGE, - number=2, - message='SummaryOptions', - ) - - -class PropertyMetadata(proto.Message): - r"""Metadata about a property. - - Attributes: - inactive (bool): - Whether the property should be considered as - "inactive". - field_extraction_metadata (google.cloud.documentai_v1beta3.types.FieldExtractionMetadata): - Field extraction metadata on the property. - """ - - inactive: bool = proto.Field( - proto.BOOL, - number=3, - ) - field_extraction_metadata: 'FieldExtractionMetadata' = proto.Field( - proto.MESSAGE, - number=9, - message='FieldExtractionMetadata', - ) - - -class EntityTypeMetadata(proto.Message): - r"""Metadata about an entity type. - - Attributes: - inactive (bool): - Whether the entity type should be considered - inactive. - """ - - inactive: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class DocumentSchema(proto.Message): - r"""The schema defines the output of the processed document by a - processor. - - Attributes: - display_name (str): - Display name to show to users. - description (str): - Description of the schema. - entity_types (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType]): - Entity types of the schema. - metadata (google.cloud.documentai_v1beta3.types.DocumentSchema.Metadata): - Metadata of the schema. - """ - - class EntityType(proto.Message): - r"""EntityType is the wrapper of a label of the corresponding - model with detailed attributes and limitations for entity-based - processors. Multiple types can also compose a dependency tree to - represent nested types. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - enum_values (google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.EnumValues): - If specified, lists all the possible values for this entity. - This should not be more than a handful of values. If the - number of values is >10 or could change frequently use the - ``EntityType.value_ontology`` field and specify a list of - all possible values in a value ontology file. - - This field is a member of `oneof`_ ``value_source``. - display_name (str): - User defined name for the type. - name (str): - Name of the type. It must be unique within the schema file - and cannot be a "Common Type". The following naming - conventions are used: - - - Use ``snake_casing``. - - Name matching is case-sensitive. - - Maximum 64 characters. - - Must start with a letter. - - Allowed characters: ASCII letters ``[a-z0-9_-]``. (For - backward compatibility internal infrastructure and - tooling can handle any ascii character.) - - The ``/`` is sometimes used to denote a property of a - type. For example ``line_item/amount``. This convention - is deprecated, but will still be honored for backward - compatibility. - base_types (MutableSequence[str]): - The entity type that this type is derived - from. For now, one and only one should be set. - properties (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentSchema.EntityType.Property]): - Description the nested structure, or - composition of an entity. - entity_type_metadata (google.cloud.documentai_v1beta3.types.EntityTypeMetadata): - Metadata for the entity type. - """ - - class EnumValues(proto.Message): - r"""Defines the a list of enum values. - - Attributes: - values (MutableSequence[str]): - The individual values that this enum values - type can include. - """ - - values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class Property(proto.Message): - r"""Defines properties that can be part of the entity type. - - Attributes: - name (str): - The name of the property. Follows the same - guidelines as the EntityType name. - display_name (str): - User defined name for the property. - 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. - property_metadata (google.cloud.documentai_v1beta3.types.PropertyMetadata): - Any additional metadata about the property - can be added here. - """ - class OccurrenceType(proto.Enum): - r"""Types of occurrences of the entity type in the document. This - represents the number of instances, not mentions, of an entity. For - example, a bank statement might only have one ``account_number``, - but this account number can be mentioned in several places on the - document. In this case, the ``account_number`` is considered a - ``REQUIRED_ONCE`` entity type. If, on the other hand, we expect a - bank statement to contain the status of multiple different accounts - for the customers, the occurrence type is set to - ``REQUIRED_MULTIPLE``. - - Values: - OCCURRENCE_TYPE_UNSPECIFIED (0): - Unspecified occurrence type. - OPTIONAL_ONCE (1): - There will be zero or one instance of this - entity type. The same entity instance may be - mentioned multiple times. - OPTIONAL_MULTIPLE (2): - The entity type will appear zero or multiple - times. - REQUIRED_ONCE (3): - The entity type will only appear exactly - once. The same entity instance may be mentioned - multiple times. - REQUIRED_MULTIPLE (4): - The entity type will appear once or more - times. - """ - OCCURRENCE_TYPE_UNSPECIFIED = 0 - OPTIONAL_ONCE = 1 - OPTIONAL_MULTIPLE = 2 - REQUIRED_ONCE = 3 - REQUIRED_MULTIPLE = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=6, - ) - value_type: str = proto.Field( - proto.STRING, - number=2, - ) - occurrence_type: 'DocumentSchema.EntityType.Property.OccurrenceType' = proto.Field( - proto.ENUM, - number=3, - enum='DocumentSchema.EntityType.Property.OccurrenceType', - ) - property_metadata: 'PropertyMetadata' = proto.Field( - proto.MESSAGE, - number=5, - message='PropertyMetadata', - ) - - enum_values: 'DocumentSchema.EntityType.EnumValues' = proto.Field( - proto.MESSAGE, - number=14, - oneof='value_source', - message='DocumentSchema.EntityType.EnumValues', - ) - display_name: str = proto.Field( - proto.STRING, - number=13, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - base_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - properties: MutableSequence['DocumentSchema.EntityType.Property'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='DocumentSchema.EntityType.Property', - ) - entity_type_metadata: 'EntityTypeMetadata' = proto.Field( - proto.MESSAGE, - number=11, - message='EntityTypeMetadata', - ) - - class Metadata(proto.Message): - r"""Metadata for global schema behavior. - - Attributes: - document_splitter (bool): - If true, a ``document`` entity type can be applied to - subdocument (splitting). Otherwise, it can only be applied - to the entire document (classification). - document_allow_multiple_labels (bool): - If true, on a given page, there can be multiple ``document`` - annotations covering it. - prefixed_naming_on_properties (bool): - If set, all the nested entities must be - prefixed with the parents. - skip_naming_validation (bool): - If set, we will skip the naming format validation in the - schema. So the string values in - ``DocumentSchema.EntityType.name`` and - ``DocumentSchema.EntityType.Property.name`` will not be - checked. - """ - - document_splitter: bool = proto.Field( - proto.BOOL, - number=1, - ) - document_allow_multiple_labels: bool = proto.Field( - proto.BOOL, - number=2, - ) - prefixed_naming_on_properties: bool = proto.Field( - proto.BOOL, - number=6, - ) - skip_naming_validation: bool = proto.Field( - proto.BOOL, - number=7, - ) - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - entity_types: MutableSequence[EntityType] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=EntityType, - ) - metadata: Metadata = proto.Field( - proto.MESSAGE, - number=4, - message=Metadata, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_service.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_service.py deleted file mode 100644 index 3ec84003122f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/document_service.py +++ /dev/null @@ -1,703 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1beta3.types import dataset as gcd_dataset -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 operation_metadata -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'DatasetSplitType', - 'DocumentLabelingState', - 'UpdateDatasetRequest', - 'UpdateDatasetOperationMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportDocumentsMetadata', - 'GetDocumentRequest', - 'GetDocumentResponse', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'BatchDeleteDocumentsRequest', - 'BatchDeleteDocumentsResponse', - 'BatchDeleteDocumentsMetadata', - 'GetDatasetSchemaRequest', - 'UpdateDatasetSchemaRequest', - 'DocumentPageRange', - 'DocumentMetadata', - }, -) - - -class DatasetSplitType(proto.Enum): - r"""Documents belonging to a dataset will be split into different - groups referred to as splits: train, test. - - Values: - DATASET_SPLIT_TYPE_UNSPECIFIED (0): - Default value if the enum is not set. - DATASET_SPLIT_TRAIN (1): - Identifies the train documents. - DATASET_SPLIT_TEST (2): - Identifies the test documents. - DATASET_SPLIT_UNASSIGNED (3): - Identifies the unassigned documents. - """ - DATASET_SPLIT_TYPE_UNSPECIFIED = 0 - DATASET_SPLIT_TRAIN = 1 - DATASET_SPLIT_TEST = 2 - DATASET_SPLIT_UNASSIGNED = 3 - - -class DocumentLabelingState(proto.Enum): - r"""Describes the labeling status of a document. - - Values: - DOCUMENT_LABELING_STATE_UNSPECIFIED (0): - Default value if the enum is not set. - DOCUMENT_LABELED (1): - Document has been labeled. - DOCUMENT_UNLABELED (2): - Document has not been labeled. - DOCUMENT_AUTO_LABELED (3): - Document has been auto-labeled. - """ - DOCUMENT_LABELING_STATE_UNSPECIFIED = 0 - DOCUMENT_LABELED = 1 - DOCUMENT_UNLABELED = 2 - DOCUMENT_AUTO_LABELED = 3 - - -class UpdateDatasetRequest(proto.Message): - r""" - - Attributes: - dataset (google.cloud.documentai_v1beta3.types.Dataset): - Required. The ``name`` field of the ``Dataset`` is used to - identify the resource to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The update mask applies to the resource. - """ - - dataset: gcd_dataset.Dataset = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_dataset.Dataset, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateDatasetOperationMetadata(proto.Message): - r""" - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - """ - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - - -class ImportDocumentsRequest(proto.Message): - r""" - - Attributes: - dataset (str): - Required. The dataset resource name. - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - batch_documents_import_configs (MutableSequence[google.cloud.documentai_v1beta3.types.ImportDocumentsRequest.BatchDocumentsImportConfig]): - Required. The Cloud Storage uri containing - raw documents that must be imported. - """ - - class BatchDocumentsImportConfig(proto.Message): - r"""Config for importing documents. - Each batch can have its own dataset split type. - - 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: - dataset_split (google.cloud.documentai_v1beta3.types.DatasetSplitType): - Target dataset split where the documents must - be stored. - - This field is a member of `oneof`_ ``split_type_config``. - auto_split_config (google.cloud.documentai_v1beta3.types.ImportDocumentsRequest.BatchDocumentsImportConfig.AutoSplitConfig): - If set, documents will be automatically split - into training and test split category with the - specified ratio. - - This field is a member of `oneof`_ ``split_type_config``. - batch_input_config (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): - The common config to specify a set of - documents used as input. - """ - - class AutoSplitConfig(proto.Message): - r"""The config for auto-split. - - Attributes: - training_split_ratio (float): - Ratio of training dataset split. - """ - - training_split_ratio: float = proto.Field( - proto.FLOAT, - number=1, - ) - - dataset_split: 'DatasetSplitType' = proto.Field( - proto.ENUM, - number=2, - oneof='split_type_config', - enum='DatasetSplitType', - ) - auto_split_config: 'ImportDocumentsRequest.BatchDocumentsImportConfig.AutoSplitConfig' = proto.Field( - proto.MESSAGE, - number=3, - oneof='split_type_config', - message='ImportDocumentsRequest.BatchDocumentsImportConfig.AutoSplitConfig', - ) - batch_input_config: document_io.BatchDocumentsInputConfig = proto.Field( - proto.MESSAGE, - number=1, - message=document_io.BatchDocumentsInputConfig, - ) - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - batch_documents_import_configs: MutableSequence[BatchDocumentsImportConfig] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=BatchDocumentsImportConfig, - ) - - -class ImportDocumentsResponse(proto.Message): - r"""Response of the import document operation. - """ - - -class ImportDocumentsMetadata(proto.Message): - r"""Metadata of the import document operation. - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - individual_import_statuses (MutableSequence[google.cloud.documentai_v1beta3.types.ImportDocumentsMetadata.IndividualImportStatus]): - The list of response details of each - document. - import_config_validation_results (MutableSequence[google.cloud.documentai_v1beta3.types.ImportDocumentsMetadata.ImportConfigValidationResult]): - Validation statuses of the batch documents - import config. - total_document_count (int): - Total number of the documents that are - qualified for importing. - """ - - class IndividualImportStatus(proto.Message): - r"""The status of each individual document in the import process. - - Attributes: - input_gcs_source (str): - The source Cloud Storage URI of the document. - status (google.rpc.status_pb2.Status): - The status of the importing of the document. - output_document_id (google.cloud.documentai_v1beta3.types.DocumentId): - The document id of imported document if it - was successful, otherwise empty. - """ - - input_gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - output_document_id: gcd_dataset.DocumentId = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_dataset.DocumentId, - ) - - class ImportConfigValidationResult(proto.Message): - r"""The validation status of each import config. Status is set to an - error if there are no documents to import in the ``import_config``, - or ``OK`` if the operation will try to proceed with at least one - document. - - Attributes: - input_gcs_source (str): - The source Cloud Storage URI specified in the - import config. - status (google.rpc.status_pb2.Status): - The validation status of import config. - """ - - input_gcs_source: str = proto.Field( - proto.STRING, - number=1, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - individual_import_statuses: MutableSequence[IndividualImportStatus] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=IndividualImportStatus, - ) - import_config_validation_results: MutableSequence[ImportConfigValidationResult] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=ImportConfigValidationResult, - ) - total_document_count: int = proto.Field( - proto.INT32, - number=3, - ) - - -class GetDocumentRequest(proto.Message): - r""" - - Attributes: - dataset (str): - Required. The resource name of the dataset - that the document belongs to . Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - document_id (google.cloud.documentai_v1beta3.types.DocumentId): - Required. Document identifier. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - If set, only fields listed here will be - returned. Otherwise, all fields will be returned - by default. - page_range (google.cloud.documentai_v1beta3.types.DocumentPageRange): - List of pages for which the fields specified in the - ``read_mask`` must be served. - """ - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - document_id: gcd_dataset.DocumentId = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_dataset.DocumentId, - ) - read_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - page_range: 'DocumentPageRange' = proto.Field( - proto.MESSAGE, - number=4, - message='DocumentPageRange', - ) - - -class GetDocumentResponse(proto.Message): - r""" - - Attributes: - document (google.cloud.documentai_v1beta3.types.Document): - - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - - -class ListDocumentsRequest(proto.Message): - r""" - - Attributes: - dataset (str): - Required. The resource name of the dataset to - be listed. Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - page_size (int): - The maximum number of documents to return. - The service may return fewer than this value. If - unspecified, at most 20 documents will be - returned. The maximum value is 100; values above - 100 will be coerced to 100. - page_token (str): - A page token, received from a previous ``ListDocuments`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListDocuments`` must match the call that provided the page - token. - filter (str): - Optional. Query to filter the documents based on - https://google.aip.dev/160. - - Currently support query strings are: - ------------------------------------ - - ``SplitType=DATASET_SPLIT_TEST|DATASET_SPLIT_TRAIN|DATASET_SPLIT_UNASSIGNED`` - - - ``LabelingState=DOCUMENT_LABELED|DOCUMENT_UNLABELED|DOCUMENT_AUTO_LABELED`` - - ``DisplayName=\"file_name.pdf\"`` - - ``EntityType=abc/def`` - - ``TagName=\"auto-labeling-running\"|\"sampled\"`` - - Note: - - - Only ``AND``, ``=`` and ``!=`` are supported. e.g. - ``DisplayName=file_name AND EntityType!=abc`` IS - supported. - - Wildcard ``*`` is supported only in ``DisplayName`` - filter - - No duplicate filter keys are allowed, e.g. - ``EntityType=a AND EntityType=b`` is NOT supported. - - String match is case sensitive (for filter - ``DisplayName`` & ``EntityType``). - return_total_size (bool): - Optional. Controls if the request requires a total size of - matched documents. See - [ListDocumentsResponse.total_size][google.cloud.documentai.v1beta3.ListDocumentsResponse.total_size]. - - Enabling this flag may adversely impact performance. - - Defaults to false. - skip (int): - Optional. Number of results to skip beginning from the - ``page_token`` if provided. - https://google.aip.dev/158#skipping-results. It must be a - non-negative integer. Negative values will be rejected. Note - that this is not the number of pages to skip. If this value - causes the cursor to move past the end of results, - [ListDocumentsResponse.document_metadata][google.cloud.documentai.v1beta3.ListDocumentsResponse.document_metadata] - and - [ListDocumentsResponse.next_page_token][google.cloud.documentai.v1beta3.ListDocumentsResponse.next_page_token] - will be empty. - """ - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - return_total_size: bool = proto.Field( - proto.BOOL, - number=6, - ) - skip: int = proto.Field( - proto.INT32, - number=8, - ) - - -class ListDocumentsResponse(proto.Message): - r""" - - Attributes: - document_metadata (MutableSequence[google.cloud.documentai_v1beta3.types.DocumentMetadata]): - Document metadata corresponding to the listed - documents. - next_page_token (str): - A token, which can be sent as - [ListDocumentsRequest.page_token][google.cloud.documentai.v1beta3.ListDocumentsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - total_size (int): - Total count of documents queried. - """ - - @property - def raw_page(self): - return self - - document_metadata: MutableSequence['DocumentMetadata'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DocumentMetadata', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class BatchDeleteDocumentsRequest(proto.Message): - r""" - - Attributes: - dataset (str): - Required. The dataset resource name. - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset - dataset_documents (google.cloud.documentai_v1beta3.types.BatchDatasetDocuments): - Required. Dataset documents input. If given ``filter``, all - documents satisfying the filter will be deleted. If given - documentIds, a maximum of 50 documents can be deleted in a - batch. The request will be rejected if more than 50 - document_ids are provided. - """ - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - dataset_documents: gcd_dataset.BatchDatasetDocuments = proto.Field( - proto.MESSAGE, - number=3, - message=gcd_dataset.BatchDatasetDocuments, - ) - - -class BatchDeleteDocumentsResponse(proto.Message): - r"""Response of the delete documents operation. - """ - - -class BatchDeleteDocumentsMetadata(proto.Message): - r""" - - Attributes: - common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): - The basic metadata of the long-running - operation. - individual_batch_delete_statuses (MutableSequence[google.cloud.documentai_v1beta3.types.BatchDeleteDocumentsMetadata.IndividualBatchDeleteStatus]): - The list of response details of each - document. - total_document_count (int): - Total number of documents deleting from - dataset. - error_document_count (int): - Total number of documents that failed to be - deleted in storage. - """ - - class IndividualBatchDeleteStatus(proto.Message): - r"""The status of each individual document in the batch delete - process. - - Attributes: - document_id (google.cloud.documentai_v1beta3.types.DocumentId): - The document id of the document. - status (google.rpc.status_pb2.Status): - The status of deleting the document in - storage. - """ - - document_id: gcd_dataset.DocumentId = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_dataset.DocumentId, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( - proto.MESSAGE, - number=1, - message=operation_metadata.CommonOperationMetadata, - ) - individual_batch_delete_statuses: MutableSequence[IndividualBatchDeleteStatus] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=IndividualBatchDeleteStatus, - ) - total_document_count: int = proto.Field( - proto.INT32, - number=3, - ) - error_document_count: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GetDatasetSchemaRequest(proto.Message): - r"""Request for ``GetDatasetSchema``. - - Attributes: - name (str): - Required. The dataset schema resource name. - Format: - - projects/{project}/locations/{location}/processors/{processor}/dataset/datasetSchema - visible_fields_only (bool): - If set, only returns the visible fields of - the schema. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - visible_fields_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class UpdateDatasetSchemaRequest(proto.Message): - r"""Request for ``UpdateDatasetSchema``. - - Attributes: - dataset_schema (google.cloud.documentai_v1beta3.types.DatasetSchema): - Required. The name field of the ``DatasetSchema`` is used to - identify the resource to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The update mask applies to the resource. - """ - - dataset_schema: gcd_dataset.DatasetSchema = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_dataset.DatasetSchema, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DocumentPageRange(proto.Message): - r"""Range of pages present in a document. - - Attributes: - start (int): - First page number (one-based index) to be - returned. - end (int): - Last page number (one-based index) to be - returned. - """ - - start: int = proto.Field( - proto.INT32, - number=1, - ) - end: int = proto.Field( - proto.INT32, - number=2, - ) - - -class DocumentMetadata(proto.Message): - r"""Metadata about a document. - - Attributes: - document_id (google.cloud.documentai_v1beta3.types.DocumentId): - Document identifier. - page_count (int): - Number of pages in the document. - dataset_type (google.cloud.documentai_v1beta3.types.DatasetSplitType): - Type of the dataset split to which the - document belongs. - labeling_state (google.cloud.documentai_v1beta3.types.DocumentLabelingState): - Labeling state of the document. - display_name (str): - The display name of the document. - """ - - document_id: gcd_dataset.DocumentId = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_dataset.DocumentId, - ) - page_count: int = proto.Field( - proto.INT32, - number=2, - ) - dataset_type: 'DatasetSplitType' = proto.Field( - proto.ENUM, - number=3, - enum='DatasetSplitType', - ) - labeling_state: 'DocumentLabelingState' = proto.Field( - proto.ENUM, - number=5, - enum='DocumentLabelingState', - ) - display_name: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py deleted file mode 100644 index fa9863620115..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/evaluation.py +++ /dev/null @@ -1,344 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'EvaluationReference', - 'Evaluation', - }, -) - - -class EvaluationReference(proto.Message): - r"""Gives a short summary of an evaluation, and links to the - evaluation itself. - - Attributes: - operation (str): - The resource name of the Long Running - Operation for the evaluation. - evaluation (str): - The resource name of the evaluation. - aggregate_metrics (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): - An aggregate of the statistics for the - evaluation with fuzzy matching on. - aggregate_metrics_exact (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): - An aggregate of the statistics for the - evaluation with fuzzy matching off. - """ - - operation: str = proto.Field( - proto.STRING, - number=1, - ) - evaluation: str = proto.Field( - proto.STRING, - number=2, - ) - aggregate_metrics: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=4, - message='Evaluation.Metrics', - ) - aggregate_metrics_exact: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=5, - message='Evaluation.Metrics', - ) - - -class Evaluation(proto.Message): - r"""An evaluation of a ProcessorVersion's performance. - - Attributes: - name (str): - The resource name of the evaluation. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the evaluation was created. - document_counters (google.cloud.documentai_v1beta3.types.Evaluation.Counters): - Counters for the documents used in the - evaluation. - all_entities_metrics (google.cloud.documentai_v1beta3.types.Evaluation.MultiConfidenceMetrics): - Metrics for all the entities in aggregate. - entity_metrics (MutableMapping[str, google.cloud.documentai_v1beta3.types.Evaluation.MultiConfidenceMetrics]): - Metrics across confidence levels, for - different entities. - kms_key_name (str): - The KMS key name used for encryption. - kms_key_version_name (str): - The KMS key version with which data is - encrypted. - """ - - class Counters(proto.Message): - r"""Evaluation counters for the documents that were used. - - Attributes: - input_documents_count (int): - How many documents were sent for evaluation. - invalid_documents_count (int): - How many documents were not included in the - evaluation as they didn't pass validation. - failed_documents_count (int): - How many documents were not included in the - evaluation as Document AI failed to process - them. - evaluated_documents_count (int): - How many documents were used in the - evaluation. - """ - - input_documents_count: int = proto.Field( - proto.INT32, - number=1, - ) - invalid_documents_count: int = proto.Field( - proto.INT32, - number=2, - ) - failed_documents_count: int = proto.Field( - proto.INT32, - number=3, - ) - evaluated_documents_count: int = proto.Field( - proto.INT32, - number=4, - ) - - class Metrics(proto.Message): - r"""Evaluation metrics, either in aggregate or about a specific - entity. - - Attributes: - precision (float): - The calculated precision. - recall (float): - The calculated recall. - f1_score (float): - The calculated f1 score. - predicted_occurrences_count (int): - The amount of occurrences in predicted - documents. - ground_truth_occurrences_count (int): - The amount of occurrences in ground truth - documents. - predicted_document_count (int): - The amount of documents with a predicted - occurrence. - ground_truth_document_count (int): - The amount of documents with a ground truth - occurrence. - true_positives_count (int): - The amount of true positives. - false_positives_count (int): - The amount of false positives. - false_negatives_count (int): - The amount of false negatives. - total_documents_count (int): - The amount of documents that had an - occurrence of this label. - """ - - precision: float = proto.Field( - proto.FLOAT, - number=1, - ) - recall: float = proto.Field( - proto.FLOAT, - number=2, - ) - f1_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - predicted_occurrences_count: int = proto.Field( - proto.INT32, - number=4, - ) - ground_truth_occurrences_count: int = proto.Field( - proto.INT32, - number=5, - ) - predicted_document_count: int = proto.Field( - proto.INT32, - number=10, - ) - ground_truth_document_count: int = proto.Field( - proto.INT32, - number=11, - ) - true_positives_count: int = proto.Field( - proto.INT32, - number=6, - ) - false_positives_count: int = proto.Field( - proto.INT32, - number=7, - ) - false_negatives_count: int = proto.Field( - proto.INT32, - number=8, - ) - total_documents_count: int = proto.Field( - proto.INT32, - number=9, - ) - - class ConfidenceLevelMetrics(proto.Message): - r"""Evaluations metrics, at a specific confidence level. - - Attributes: - confidence_level (float): - The confidence level. - metrics (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): - The metrics at the specific confidence level. - """ - - confidence_level: float = proto.Field( - proto.FLOAT, - number=1, - ) - metrics: 'Evaluation.Metrics' = proto.Field( - proto.MESSAGE, - number=2, - message='Evaluation.Metrics', - ) - - class MultiConfidenceMetrics(proto.Message): - r"""Metrics across multiple confidence levels. - - Attributes: - confidence_level_metrics (MutableSequence[google.cloud.documentai_v1beta3.types.Evaluation.ConfidenceLevelMetrics]): - Metrics across confidence levels with fuzzy - matching enabled. - confidence_level_metrics_exact (MutableSequence[google.cloud.documentai_v1beta3.types.Evaluation.ConfidenceLevelMetrics]): - Metrics across confidence levels with only - exact matching. - auprc (float): - The calculated area under the precision - recall curve (AUPRC), computed by integrating - over all confidence thresholds. - estimated_calibration_error (float): - The Estimated Calibration Error (ECE) of the - confidence of the predicted entities. - auprc_exact (float): - The AUPRC for metrics with fuzzy matching - disabled, i.e., exact matching only. - estimated_calibration_error_exact (float): - The ECE for the predicted entities with fuzzy - matching disabled, i.e., exact matching only. - metrics_type (google.cloud.documentai_v1beta3.types.Evaluation.MultiConfidenceMetrics.MetricsType): - The metrics type for the label. - """ - class MetricsType(proto.Enum): - r"""A type that determines how metrics should be interpreted. - - Values: - METRICS_TYPE_UNSPECIFIED (0): - The metrics type is unspecified. By default, - metrics without a particular specification are - for leaf entity types (i.e., top-level entity - types without child types, or child types which - are not parent types themselves). - AGGREGATE (1): - Indicates whether metrics for this particular - label type represent an aggregate of metrics for - other types instead of being based on actual - TP/FP/FN values for the label type. Metrics for - parent (i.e., non-leaf) entity types are an - aggregate of metrics for their children. - """ - METRICS_TYPE_UNSPECIFIED = 0 - AGGREGATE = 1 - - confidence_level_metrics: MutableSequence['Evaluation.ConfidenceLevelMetrics'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Evaluation.ConfidenceLevelMetrics', - ) - confidence_level_metrics_exact: MutableSequence['Evaluation.ConfidenceLevelMetrics'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Evaluation.ConfidenceLevelMetrics', - ) - auprc: float = proto.Field( - proto.FLOAT, - number=2, - ) - estimated_calibration_error: float = proto.Field( - proto.FLOAT, - number=3, - ) - auprc_exact: float = proto.Field( - proto.FLOAT, - number=5, - ) - estimated_calibration_error_exact: float = proto.Field( - proto.FLOAT, - number=6, - ) - metrics_type: 'Evaluation.MultiConfidenceMetrics.MetricsType' = proto.Field( - proto.ENUM, - number=7, - enum='Evaluation.MultiConfidenceMetrics.MetricsType', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - document_counters: Counters = proto.Field( - proto.MESSAGE, - number=5, - message=Counters, - ) - all_entities_metrics: MultiConfidenceMetrics = proto.Field( - proto.MESSAGE, - number=3, - message=MultiConfidenceMetrics, - ) - entity_metrics: MutableMapping[str, MultiConfidenceMetrics] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=MultiConfidenceMetrics, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=6, - ) - kms_key_version_name: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py deleted file mode 100644 index b0dfe5f0e041..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/geometry.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'Vertex', - 'NormalizedVertex', - 'BoundingPoly', - }, -) - - -class Vertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the vertex coordinates are in the same scale as the - original image. - - Attributes: - x (int): - X coordinate. - y (int): - Y coordinate (starts from the top of the - image). - """ - - x: int = proto.Field( - proto.INT32, - number=1, - ) - y: int = proto.Field( - proto.INT32, - number=2, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate (starts from the top of the - image). - """ - - x: float = proto.Field( - proto.FLOAT, - number=1, - ) - y: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class BoundingPoly(proto.Message): - r"""A bounding polygon for the detected image annotation. - - Attributes: - vertices (MutableSequence[google.cloud.documentai_v1beta3.types.Vertex]): - The bounding polygon vertices. - normalized_vertices (MutableSequence[google.cloud.documentai_v1beta3.types.NormalizedVertex]): - The bounding polygon normalized vertices. - """ - - vertices: MutableSequence['Vertex'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py deleted file mode 100644 index d7666cdf576b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/operation_metadata.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'CommonOperationMetadata', - }, -) - - -class CommonOperationMetadata(proto.Message): - r"""The common metadata for long running operations. - - Attributes: - state (google.cloud.documentai_v1beta3.types.CommonOperationMetadata.State): - The state of the operation. - state_message (str): - A message providing more details about the - current state of processing. - resource (str): - A related resource to this operation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - """ - class State(proto.Enum): - r"""State of the longrunning operation. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - RUNNING (1): - Operation is still running. - CANCELLING (2): - Operation is being cancelled. - SUCCEEDED (3): - Operation succeeded. - FAILED (4): - Operation failed. - CANCELLED (5): - Operation is cancelled. - """ - STATE_UNSPECIFIED = 0 - RUNNING = 1 - CANCELLING = 2 - SUCCEEDED = 3 - FAILED = 4 - CANCELLED = 5 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - resource: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/processor.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/processor.py deleted file mode 100644 index 76d73e7cbf3f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/processor.py +++ /dev/null @@ -1,344 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.documentai_v1beta3.types import document_schema as gcd_document_schema -from google.cloud.documentai_v1beta3.types import evaluation -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'ProcessorVersion', - 'ProcessorVersionAlias', - 'Processor', - }, -) - - -class ProcessorVersion(proto.Message): - r"""A processor version is an implementation of a processor. Each - processor can have multiple versions, pretrained by Google - internally or uptrained by the customer. A processor can only - have one default version at a time. Its document-processing - behavior is defined by that version. - - Attributes: - name (str): - The resource name of the processor version. Format: - ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}`` - display_name (str): - The display name of the processor version. - document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): - The schema of the processor version. - Describes the output. - state (google.cloud.documentai_v1beta3.types.ProcessorVersion.State): - The state of the processor version. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the processor version was created. - latest_evaluation (google.cloud.documentai_v1beta3.types.EvaluationReference): - The most recently invoked evaluation for the - processor version. - kms_key_name (str): - The KMS key name used for encryption. - kms_key_version_name (str): - The KMS key version with which data is - encrypted. - google_managed (bool): - Output only. 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. - model_type (google.cloud.documentai_v1beta3.types.ProcessorVersion.ModelType): - Output only. The model type of this processor - version. - """ - class State(proto.Enum): - r"""The possible states of the processor version. - - Values: - STATE_UNSPECIFIED (0): - The processor version is in an unspecified - state. - DEPLOYED (1): - The processor version is deployed and can be - used for processing. - DEPLOYING (2): - The processor version is being deployed. - UNDEPLOYED (3): - The processor version is not deployed and - cannot be used for processing. - UNDEPLOYING (4): - The processor version is being undeployed. - CREATING (5): - The processor version is being created. - DELETING (6): - The processor version is being deleted. - FAILED (7): - The processor version failed and is in an - indeterminate state. - IMPORTING (8): - The processor version is being imported. - """ - STATE_UNSPECIFIED = 0 - DEPLOYED = 1 - DEPLOYING = 2 - UNDEPLOYED = 3 - UNDEPLOYING = 4 - CREATING = 5 - DELETING = 6 - FAILED = 7 - IMPORTING = 8 - - class ModelType(proto.Enum): - r"""The possible model types of the processor version. - - Values: - MODEL_TYPE_UNSPECIFIED (0): - The processor version has unspecified model - type. - MODEL_TYPE_GENERATIVE (1): - The processor version has generative model - type. - MODEL_TYPE_CUSTOM (2): - The processor version has custom model type. - """ - MODEL_TYPE_UNSPECIFIED = 0 - MODEL_TYPE_GENERATIVE = 1 - MODEL_TYPE_CUSTOM = 2 - - class DeprecationInfo(proto.Message): - r"""Information about the upcoming deprecation of this processor - version. - - Attributes: - deprecation_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which this processor version will - be deprecated. - replacement_processor_version (str): - If set, the processor version that will be - used as a replacement. - """ - - deprecation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - replacement_processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - document_schema: gcd_document_schema.DocumentSchema = proto.Field( - proto.MESSAGE, - number=12, - message=gcd_document_schema.DocumentSchema, - ) - state: State = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - latest_evaluation: evaluation.EvaluationReference = proto.Field( - proto.MESSAGE, - number=8, - message=evaluation.EvaluationReference, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=9, - ) - kms_key_version_name: str = proto.Field( - proto.STRING, - number=10, - ) - google_managed: bool = proto.Field( - proto.BOOL, - number=11, - ) - deprecation_info: DeprecationInfo = proto.Field( - proto.MESSAGE, - number=13, - message=DeprecationInfo, - ) - model_type: ModelType = proto.Field( - proto.ENUM, - number=15, - enum=ModelType, - ) - - -class ProcessorVersionAlias(proto.Message): - r"""Contains the alias and the aliased resource name of processor - version. - - Attributes: - alias (str): - The alias in the form of ``processor_version`` resource - name. - processor_version (str): - The resource name of aliased processor - version. - """ - - alias: str = proto.Field( - proto.STRING, - number=1, - ) - processor_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -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, such as: ``OCR_PROCESSOR``, - ``INVOICE_PROCESSOR``. To get a list of processor 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. - processor_version_aliases (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorVersionAlias]): - Output only. The processor version aliases. - 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 and decryption in CMEK scenarios. - """ - class State(proto.Enum): - r"""The possible states of the processor. - - Values: - STATE_UNSPECIFIED (0): - The processor is in an unspecified state. - ENABLED (1): - The processor is enabled, i.e., has an - enabled version which can currently serve - processing requests and all the feature - dependencies have been successfully initialized. - DISABLED (2): - The processor is disabled. - ENABLING (3): - The processor is being enabled, will become ``ENABLED`` if - successful. - DISABLING (4): - The processor is being disabled, will become ``DISABLED`` if - successful. - CREATING (5): - The processor is being created, will become either - ``ENABLED`` (for successful creation) or ``FAILED`` (for - failed ones). Once a processor is in this state, it can then - be used for document processing, but the feature - dependencies of the processor might not be fully created - yet. - FAILED (6): - The processor failed during creation or - initialization of feature dependencies. The user - should delete the processor and recreate one as - all the functionalities of the processor are - disabled. - DELETING (7): - The processor is being deleted, will be - removed if successful. - """ - STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - ENABLING = 3 - DISABLING = 4 - CREATING = 5 - FAILED = 6 - DELETING = 7 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - default_processor_version: str = proto.Field( - proto.STRING, - number=9, - ) - processor_version_aliases: MutableSequence['ProcessorVersionAlias'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='ProcessorVersionAlias', - ) - process_endpoint: str = proto.Field( - proto.STRING, - number=6, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py b/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py deleted file mode 100644 index bc642950b06f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/google/cloud/documentai_v1beta3/types/processor_type.py +++ /dev/null @@ -1,109 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.api import launch_stage_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.documentai.v1beta3', - manifest={ - 'ProcessorType', - }, -) - - -class ProcessorType(proto.Message): - r"""A processor type is responsible for performing a certain - document understanding task on a certain type of document. - - Attributes: - name (str): - The resource name of the processor type. Format: - ``projects/{project}/processorTypes/{processor_type}`` - type_ (str): - The processor type, such as: ``OCR_PROCESSOR``, - ``INVOICE_PROCESSOR``. - category (str): - The processor category, used by UI to group - processor types. - available_locations (MutableSequence[google.cloud.documentai_v1beta3.types.ProcessorType.LocationInfo]): - The locations in which this processor is - available. - allow_creation (bool): - Whether the processor type allows creation. - If true, users can create a processor of this - processor type. Otherwise, users need to request - access. - launch_stage (google.api.launch_stage_pb2.LaunchStage): - Launch stage of the processor type - sample_document_uris (MutableSequence[str]): - A set of Cloud Storage URIs of sample - documents for this processor. - """ - - class LocationInfo(proto.Message): - r"""The location information about where the processor is - available. - - Attributes: - location_id (str): - The location ID. For supported locations, refer to `regional - and multi-regional support `__. - """ - - location_id: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - category: str = proto.Field( - proto.STRING, - number=3, - ) - available_locations: MutableSequence[LocationInfo] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=LocationInfo, - ) - allow_creation: bool = proto.Field( - proto.BOOL, - number=6, - ) - launch_stage: launch_stage_pb2.LaunchStage = proto.Field( - proto.ENUM, - number=8, - enum=launch_stage_pb2.LaunchStage, - ) - sample_document_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/mypy.ini b/owl-bot-staging/google-cloud-documentai/v1beta3/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/noxfile.py b/owl-bot-staging/google-cloud-documentai/v1beta3/noxfile.py deleted file mode 100644 index bb8b2141a826..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/noxfile.py +++ /dev/null @@ -1,253 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-documentai' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@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=ALL_PYTHON[-1]) -def prerelease_deps(session): - """Run the unit test suite against pre-release versions of dependencies.""" - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/documentai_v1beta3/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - '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==7.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, - ) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py deleted file mode 100644 index 36f5daa1910e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py deleted file mode 100644 index 3561b82df1dc..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py deleted file mode 100644 index 2d276bfcbb48..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py deleted file mode 100644 index 3143028670e7..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_create_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py deleted file mode 100644 index 477a1f73c8be..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py deleted file mode 100644 index afc963a09f07..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py deleted file mode 100644 index dc4f9ecceaaf..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py deleted file mode 100644 index dce73d6e9260..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py deleted file mode 100644 index 137faf7bc673..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py deleted file mode 100644 index 5737288b6ef1..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py deleted file mode 100644 index d3716af5640d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py deleted file mode 100644 index 9a6be05a1f2c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py deleted file mode 100644 index e5f2807a7ba6..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py deleted file mode 100644 index 2f053d7b479f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py deleted file mode 100644 index 211809842bf0..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EvaluateProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -async def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py deleted file mode 100644 index bc7c1fc728ad..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EvaluateProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -def sample_evaluate_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.EvaluateProcessorVersionRequest( - processor_version="processor_version_value", - ) - - # Make the request - operation = client.evaluate_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py deleted file mode 100644 index 7e3050ac261e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py deleted file mode 100644 index 404d4fee2561..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py deleted file mode 100644 index ad6b11d895c3..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -async def sample_get_evaluation(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_evaluation(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py deleted file mode 100644 index c231dbbb9185..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -def sample_get_evaluation(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetEvaluationRequest( - name="name_value", - ) - - # Make the request - response = client.get_evaluation(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py deleted file mode 100644 index 7d14ec7ecbc0..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py deleted file mode 100644 index f7b710b53474..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py deleted file mode 100644 index 3afc3f256290..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProcessorType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -async def sample_get_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py deleted file mode 100644 index 8fe8c82e4ae9..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProcessorType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -def sample_get_processor_type(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetProcessorTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_processor_type(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py deleted file mode 100644 index fe1f2e606ad8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py deleted file mode 100644 index 980df0fad6ff..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_import_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_import_processor_version_async.py deleted file mode 100644 index ba60c61fe6b4..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_import_processor_version_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ImportProcessorVersion -# 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_ImportProcessorVersion_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_import_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ImportProcessorVersionRequest( - processor_version_source="processor_version_source_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ImportProcessorVersion_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_import_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_import_processor_version_sync.py deleted file mode 100644 index 3d3a68f49188..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_import_processor_version_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ImportProcessorVersion -# 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_ImportProcessorVersion_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_import_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ImportProcessorVersionRequest( - processor_version_source="processor_version_source_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ImportProcessorVersion_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py deleted file mode 100644 index 87d133d04d2c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEvaluations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -async def sample_list_evaluations(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py deleted file mode 100644 index 32096fc451a3..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEvaluations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -def sample_list_evaluations(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_evaluations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py deleted file mode 100644 index d22e2b4b481c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py deleted file mode 100644 index 1c55e25b9a40..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py deleted file mode 100644 index f09bfbb98c73..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py deleted file mode 100644 index 6af4402895bd..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py deleted file mode 100644 index f8bd2abcf405..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py deleted file mode 100644 index 0d1f77b88e99..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_processors_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py deleted file mode 100644 index 11fe237133de..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py deleted file mode 100644 index 198b580d34e8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_process_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py deleted file mode 100644 index 6d5c4c3355d8..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py deleted file mode 100644 index d26124afbfe2..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_review_document_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py deleted file mode 100644 index 8c17e0357812..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py deleted file mode 100644 index 11b50b193c01..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py deleted file mode 100644 index db4f90eaebda..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -async def sample_train_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py deleted file mode 100644 index c7cd29a96a9e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainProcessorVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-documentai - - -# [START documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import documentai_v1beta3 - - -def sample_train_processor_version(): - # Create a client - client = documentai_v1beta3.DocumentProcessorServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.TrainProcessorVersionRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_processor_version(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py deleted file mode 100644 index 060753fe342f..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py deleted file mode 100644 index 63b9f9b8e831..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_batch_delete_documents_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_batch_delete_documents_async.py deleted file mode 100644 index a6407ad03c06..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_batch_delete_documents_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 BatchDeleteDocuments -# 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_DocumentService_BatchDeleteDocuments_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_delete_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - dataset_documents = documentai_v1beta3.BatchDatasetDocuments() - dataset_documents.individual_document_ids.document_ids.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.BatchDeleteDocumentsRequest( - dataset="dataset_value", - dataset_documents=dataset_documents, - ) - - # Make the request - operation = client.batch_delete_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_BatchDeleteDocuments_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_batch_delete_documents_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_batch_delete_documents_sync.py deleted file mode 100644 index e03fbb15b15b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_batch_delete_documents_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 BatchDeleteDocuments -# 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_DocumentService_BatchDeleteDocuments_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_delete_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - dataset_documents = documentai_v1beta3.BatchDatasetDocuments() - dataset_documents.individual_document_ids.document_ids.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.BatchDeleteDocumentsRequest( - dataset="dataset_value", - dataset_documents=dataset_documents, - ) - - # Make the request - operation = client.batch_delete_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_BatchDeleteDocuments_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_dataset_schema_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_dataset_schema_async.py deleted file mode 100644 index f25ca011736c..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_dataset_schema_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 GetDatasetSchema -# 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_DocumentService_GetDatasetSchema_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_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetDatasetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_dataset_schema(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_GetDatasetSchema_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_dataset_schema_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_dataset_schema_sync.py deleted file mode 100644 index 382d6df5fe5a..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_dataset_schema_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 GetDatasetSchema -# 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_DocumentService_GetDatasetSchema_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_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.GetDatasetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_dataset_schema(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_GetDatasetSchema_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_document_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_document_async.py deleted file mode 100644 index 86970bab9738..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 GetDocument -# 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_DocumentService_GetDocument_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_document(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - document_id = documentai_v1beta3.DocumentId() - document_id.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.GetDocumentRequest( - dataset="dataset_value", - document_id=document_id, - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_GetDocument_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_document_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_document_sync.py deleted file mode 100644 index 3d1209ed451d..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_get_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 GetDocument -# 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_DocumentService_GetDocument_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_document(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - document_id = documentai_v1beta3.DocumentId() - document_id.gcs_managed_doc_id.gcs_uri = "gcs_uri_value" - - request = documentai_v1beta3.GetDocumentRequest( - dataset="dataset_value", - document_id=document_id, - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_GetDocument_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_import_documents_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_import_documents_async.py deleted file mode 100644 index 597f42d10e02..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_import_documents_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ImportDocuments -# 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_DocumentService_ImportDocuments_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_import_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - batch_documents_import_configs = documentai_v1beta3.BatchDocumentsImportConfig() - batch_documents_import_configs.dataset_split = "DATASET_SPLIT_UNASSIGNED" - - request = documentai_v1beta3.ImportDocumentsRequest( - dataset="dataset_value", - batch_documents_import_configs=batch_documents_import_configs, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_ImportDocuments_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_import_documents_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_import_documents_sync.py deleted file mode 100644 index 1482caa8ad41..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_import_documents_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ImportDocuments -# 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_DocumentService_ImportDocuments_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_import_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - batch_documents_import_configs = documentai_v1beta3.BatchDocumentsImportConfig() - batch_documents_import_configs.dataset_split = "DATASET_SPLIT_UNASSIGNED" - - request = documentai_v1beta3.ImportDocumentsRequest( - dataset="dataset_value", - batch_documents_import_configs=batch_documents_import_configs, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_ImportDocuments_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_list_documents_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_list_documents_async.py deleted file mode 100644 index c1a07a24f351..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_list_documents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ListDocuments -# 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_DocumentService_ListDocuments_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_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListDocumentsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentService_ListDocuments_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_list_documents_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_list_documents_sync.py deleted file mode 100644 index 1d3564dc4a69..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_list_documents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ListDocuments -# 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_DocumentService_ListDocuments_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_documents(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.ListDocumentsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END documentai_v1beta3_generated_DocumentService_ListDocuments_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_async.py deleted file mode 100644 index ed4bb69178ed..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 UpdateDataset -# 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_DocumentService_UpdateDataset_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_update_dataset(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - dataset = documentai_v1beta3.Dataset() - dataset.state = "INITIALIZED" - - request = documentai_v1beta3.UpdateDatasetRequest( - dataset=dataset, - ) - - # Make the request - operation = client.update_dataset(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_UpdateDataset_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_schema_async.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_schema_async.py deleted file mode 100644 index 6363586ebb17..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_schema_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 UpdateDatasetSchema -# 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_DocumentService_UpdateDatasetSchema_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_update_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UpdateDatasetSchemaRequest( - ) - - # Make the request - response = await client.update_dataset_schema(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_UpdateDatasetSchema_async] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_schema_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_schema_sync.py deleted file mode 100644 index 191ccb20c070..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_schema_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 UpdateDatasetSchema -# 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_DocumentService_UpdateDatasetSchema_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_update_dataset_schema(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - request = documentai_v1beta3.UpdateDatasetSchemaRequest( - ) - - # Make the request - response = client.update_dataset_schema(request=request) - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_UpdateDatasetSchema_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_sync.py b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_sync.py deleted file mode 100644 index f9285c0b8c46..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/documentai_v1beta3_generated_document_service_update_dataset_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 UpdateDataset -# 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_DocumentService_UpdateDataset_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_update_dataset(): - # Create a client - client = documentai_v1beta3.DocumentServiceClient() - - # Initialize request argument(s) - dataset = documentai_v1beta3.Dataset() - dataset.state = "INITIALIZED" - - request = documentai_v1beta3.UpdateDatasetRequest( - dataset=dataset, - ) - - # Make the request - operation = client.update_dataset(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END documentai_v1beta3_generated_DocumentService_UpdateDataset_sync] diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json b/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json deleted file mode 100644 index f47545a8ed3e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json +++ /dev/null @@ -1,4853 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.documentai.v1beta3", - "version": "v1beta3" - } - ], - "language": "PYTHON", - "name": "google-cloud-documentai", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.BatchProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.batch_process_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.BatchProcessDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "BatchProcessDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.BatchProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_process_documents" - }, - "description": "Sample for BatchProcessDocuments", - "file": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_BatchProcessDocuments_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_batch_process_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1beta3.types.Processor" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_create_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_create_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.create_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.CreateProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "CreateProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.CreateProcessorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor", - "type": "google.cloud.documentai_v1beta3.types.Processor" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.Processor", - "shortName": "create_processor" - }, - "description": "Sample for CreateProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_create_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_CreateProcessor_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_create_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.delete_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_processor_version" - }, - "description": "Sample for DeleteProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_delete_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_delete_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.delete_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeleteProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeleteProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeleteProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_processor" - }, - "description": "Sample for DeleteProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeleteProcessor_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_delete_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.deploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "deploy_processor_version" - }, - "description": "Sample for DeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DeployProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_deploy_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DisableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_disable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_disable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.disable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.DisableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "DisableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.DisableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "disable_processor" - }, - "description": "Sample for DisableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_DisableProcessor_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_disable_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.EnableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_enable_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_enable_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.enable_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EnableProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EnableProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.EnableProcessorRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "enable_processor" - }, - "description": "Sample for EnableProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EnableProcessor_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.evaluate_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EvaluateProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest" - }, - { - "name": "processor_version", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "evaluate_processor_version" - }, - "description": "Sample for EvaluateProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.evaluate_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "EvaluateProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest" - }, - { - "name": "processor_version", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "evaluate_processor_version" - }, - "description": "Sample for EvaluateProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.fetch_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "FetchProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesResponse", - "shortName": "fetch_processor_types" - }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.fetch_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "FetchProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesResponse", - "shortName": "fetch_processor_types" - }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_evaluation", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetEvaluation", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetEvaluationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.Evaluation", - "shortName": "get_evaluation" - }, - "description": "Sample for GetEvaluation", - "file": "documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_evaluation", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetEvaluation", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetEvaluationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.Evaluation", - "shortName": "get_evaluation" - }, - "description": "Sample for GetEvaluation", - "file": "documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor_type", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor_type", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorType", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessorType", - "shortName": "get_processor_type" - }, - "description": "Sample for GetProcessorType", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorType_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessorVersion", - "shortName": "get_processor_version" - }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessorVersion", - "shortName": "get_processor_version" - }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.Processor", - "shortName": "get_processor" - }, - "description": "Sample for GetProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "GetProcessor" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.Processor", - "shortName": "get_processor" - }, - "description": "Sample for GetProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.import_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ImportProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ImportProcessorVersionRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "import_processor_version" - }, - "description": "Sample for ImportProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_import_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ImportProcessorVersion_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_import_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.import_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ImportProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ImportProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ImportProcessorVersionRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "import_processor_version" - }, - "description": "Sample for ImportProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_import_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ImportProcessorVersion_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_import_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsAsyncPager", - "shortName": "list_evaluations" - }, - "description": "Sample for ListEvaluations", - "file": "documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_evaluations", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsPager", - "shortName": "list_evaluations" - }, - "description": "Sample for ListEvaluations", - "file": "documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorTypesAsyncPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processor_types", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorTypes", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorTypesPager", - "shortName": "list_processor_types" - }, - "description": "Sample for ListProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorVersionsAsyncPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processor_versions", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessorVersions", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessorVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorVersionsPager", - "shortName": "list_processor_versions" - }, - "description": "Sample for ListProcessorVersions", - "file": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessorVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processor_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorsAsyncPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1beta3_generated_document_processor_service_list_processors_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processors_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_processors", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ListProcessors" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListProcessorsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListProcessorsPager", - "shortName": "list_processors" - }, - "description": "Sample for ListProcessors", - "file": "documentai_v1beta3_generated_document_processor_service_list_processors_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListProcessors_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_list_processors_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta3_generated_document_processor_service_process_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_process_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.process_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ProcessDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ProcessDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ProcessRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessResponse", - "shortName": "process_document" - }, - "description": "Sample for ProcessDocument", - "file": "documentai_v1beta3_generated_document_processor_service_process_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ProcessDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_process_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1beta3_generated_document_processor_service_review_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_review_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.review_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ReviewDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "ReviewDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ReviewDocumentRequest" - }, - { - "name": "human_review_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "review_document" - }, - "description": "Sample for ReviewDocument", - "file": "documentai_v1beta3_generated_document_processor_service_review_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ReviewDocument_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_review_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.set_default_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.SetDefaultProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "SetDefaultProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.SetDefaultProcessorVersionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_default_processor_version" - }, - "description": "Sample for SetDefaultProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_SetDefaultProcessorVersion_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.train_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "TrainProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor_version", - "type": "google.cloud.documentai_v1beta3.types.ProcessorVersion" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "train_processor_version" - }, - "description": "Sample for TrainProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.train_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "TrainProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "processor_version", - "type": "google.cloud.documentai_v1beta3.types.ProcessorVersion" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "train_processor_version" - }, - "description": "Sample for TrainProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", - "shortName": "DocumentProcessorServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", - "shortName": "DocumentProcessorServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.undeploy_processor_version", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.UndeployProcessorVersion", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", - "shortName": "DocumentProcessorService" - }, - "shortName": "UndeployProcessorVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UndeployProcessorVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "undeploy_processor_version" - }, - "description": "Sample for UndeployProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_UndeployProcessorVersion_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_processor_service_undeploy_processor_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient.batch_delete_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.BatchDeleteDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "BatchDeleteDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.BatchDeleteDocumentsRequest" - }, - { - "name": "dataset", - "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_delete_documents" - }, - "description": "Sample for BatchDeleteDocuments", - "file": "documentai_v1beta3_generated_document_service_batch_delete_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_BatchDeleteDocuments_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_service_batch_delete_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient.batch_delete_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.BatchDeleteDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "BatchDeleteDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.BatchDeleteDocumentsRequest" - }, - { - "name": "dataset", - "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_delete_documents" - }, - "description": "Sample for BatchDeleteDocuments", - "file": "documentai_v1beta3_generated_document_service_batch_delete_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_BatchDeleteDocuments_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_service_batch_delete_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient.get_dataset_schema", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.GetDatasetSchema", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDatasetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetDatasetSchemaRequest" - }, - { - "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.DatasetSchema", - "shortName": "get_dataset_schema" - }, - "description": "Sample for GetDatasetSchema", - "file": "documentai_v1beta3_generated_document_service_get_dataset_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_GetDatasetSchema_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_service_get_dataset_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient.get_dataset_schema", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.GetDatasetSchema", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDatasetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetDatasetSchemaRequest" - }, - { - "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.DatasetSchema", - "shortName": "get_dataset_schema" - }, - "description": "Sample for GetDatasetSchema", - "file": "documentai_v1beta3_generated_document_service_get_dataset_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_GetDatasetSchema_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_service_get_dataset_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient.get_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetDocumentRequest" - }, - { - "name": "dataset", - "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.GetDocumentResponse", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "documentai_v1beta3_generated_document_service_get_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_GetDocument_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_service_get_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient.get_document", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetDocumentRequest" - }, - { - "name": "dataset", - "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.GetDocumentResponse", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "documentai_v1beta3_generated_document_service_get_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_GetDocument_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_service_get_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient.import_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ImportDocumentsRequest" - }, - { - "name": "dataset", - "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": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "documentai_v1beta3_generated_document_service_import_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_ImportDocuments_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_service_import_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient.import_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ImportDocumentsRequest" - }, - { - "name": "dataset", - "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": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "documentai_v1beta3_generated_document_service_import_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_ImportDocuments_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_service_import_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient.list_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListDocumentsRequest" - }, - { - "name": "dataset", - "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_service.pagers.ListDocumentsAsyncPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "documentai_v1beta3_generated_document_service_list_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_ListDocuments_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_service_list_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient.list_documents", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.ListDocumentsRequest" - }, - { - "name": "dataset", - "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_service.pagers.ListDocumentsPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "documentai_v1beta3_generated_document_service_list_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_ListDocuments_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_service_list_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient.update_dataset_schema", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.UpdateDatasetSchema", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDatasetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UpdateDatasetSchemaRequest" - }, - { - "name": "dataset_schema", - "type": "google.cloud.documentai_v1beta3.types.DatasetSchema" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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.DatasetSchema", - "shortName": "update_dataset_schema" - }, - "description": "Sample for UpdateDatasetSchema", - "file": "documentai_v1beta3_generated_document_service_update_dataset_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_UpdateDatasetSchema_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_service_update_dataset_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient.update_dataset_schema", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.UpdateDatasetSchema", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDatasetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UpdateDatasetSchemaRequest" - }, - { - "name": "dataset_schema", - "type": "google.cloud.documentai_v1beta3.types.DatasetSchema" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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.DatasetSchema", - "shortName": "update_dataset_schema" - }, - "description": "Sample for UpdateDatasetSchema", - "file": "documentai_v1beta3_generated_document_service_update_dataset_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_UpdateDatasetSchema_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_service_update_dataset_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceAsyncClient.update_dataset", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.UpdateDataset", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UpdateDatasetRequest" - }, - { - "name": "dataset", - "type": "google.cloud.documentai_v1beta3.types.Dataset" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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": "update_dataset" - }, - "description": "Sample for UpdateDataset", - "file": "documentai_v1beta3_generated_document_service_update_dataset_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_UpdateDataset_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_service_update_dataset_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.documentai_v1beta3.DocumentServiceClient.update_dataset", - "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService.UpdateDataset", - "service": { - "fullName": "google.cloud.documentai.v1beta3.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.documentai_v1beta3.types.UpdateDatasetRequest" - }, - { - "name": "dataset", - "type": "google.cloud.documentai_v1beta3.types.Dataset" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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": "update_dataset" - }, - "description": "Sample for UpdateDataset", - "file": "documentai_v1beta3_generated_document_service_update_dataset_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentService_UpdateDataset_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "documentai_v1beta3_generated_document_service_update_dataset_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py b/owl-bot-staging/google-cloud-documentai/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py deleted file mode 100644 index f0b457f6b1c0..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/scripts/fixup_documentai_v1beta3_keywords.py +++ /dev/null @@ -1,205 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_delete_documents': ('dataset', 'dataset_documents', ), - 'batch_process_documents': ('name', 'input_configs', 'output_config', 'input_documents', 'document_output_config', 'skip_human_review', 'process_options', 'labels', ), - 'create_processor': ('parent', 'processor', ), - 'delete_processor': ('name', ), - 'delete_processor_version': ('name', ), - 'deploy_processor_version': ('name', ), - 'disable_processor': ('name', ), - 'enable_processor': ('name', ), - 'evaluate_processor_version': ('processor_version', 'evaluation_documents', ), - 'fetch_processor_types': ('parent', ), - 'get_dataset_schema': ('name', 'visible_fields_only', ), - 'get_document': ('dataset', 'document_id', 'read_mask', 'page_range', ), - 'get_evaluation': ('name', ), - 'get_processor': ('name', ), - 'get_processor_type': ('name', ), - 'get_processor_version': ('name', ), - 'import_documents': ('dataset', 'batch_documents_import_configs', ), - 'import_processor_version': ('parent', 'processor_version_source', 'external_processor_version_source', ), - 'list_documents': ('dataset', 'page_size', 'page_token', 'filter', 'return_total_size', 'skip', ), - 'list_evaluations': ('parent', 'page_size', 'page_token', ), - 'list_processors': ('parent', 'page_size', 'page_token', ), - 'list_processor_types': ('parent', 'page_size', 'page_token', ), - 'list_processor_versions': ('parent', 'page_size', 'page_token', ), - 'process_document': ('name', 'inline_document', 'raw_document', 'gcs_document', 'document', 'skip_human_review', 'field_mask', 'process_options', 'labels', ), - 'review_document': ('human_review_config', 'inline_document', 'document', 'enable_schema_validation', 'priority', 'document_schema', ), - 'set_default_processor_version': ('processor', 'default_processor_version', ), - 'train_processor_version': ('parent', 'processor_version', 'custom_document_extraction_options', 'foundation_model_tuning_options', 'document_schema', 'input_data', 'base_processor_version', ), - 'undeploy_processor_version': ('name', ), - 'update_dataset': ('dataset', 'update_mask', ), - 'update_dataset_schema': ('dataset_schema', 'update_mask', ), - } - - 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/google-cloud-documentai/v1beta3/setup.py b/owl-bot-staging/google-cloud-documentai/v1beta3/setup.py deleted file mode 100644 index 11e72a1d001b..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/setup.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re - -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 = None - -with open(os.path.join(package_root, 'google/cloud/documentai/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <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/google-cloud-python/tree/main/packages/google-cloud-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.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.7.txt deleted file mode 100644 index b8a550c73855..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-documentai/v1beta3/tests/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta3/tests/unit/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta3/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py b/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py b/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py deleted file mode 100644 index 5527b8299a3e..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py +++ /dev/null @@ -1,14031 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.documentai_v1beta3.services.document_processor_service import DocumentProcessorServiceAsyncClient -from google.cloud.documentai_v1beta3.services.document_processor_service import DocumentProcessorServiceClient -from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.services.document_processor_service import transports -from google.cloud.documentai_v1beta3.types import barcode -from google.cloud.documentai_v1beta3.types import document -from google.cloud.documentai_v1beta3.types import document_io -from google.cloud.documentai_v1beta3.types import document_processor_service -from google.cloud.documentai_v1beta3.types import document_schema -from google.cloud.documentai_v1beta3.types import evaluation -from google.cloud.documentai_v1beta3.types import geometry -from google.cloud.documentai_v1beta3.types import processor -from google.cloud.documentai_v1beta3.types import processor as gcd_processor -from google.cloud.documentai_v1beta3.types import processor_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 - -def test__read_environment_variables(): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DocumentProcessorServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentProcessorServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert DocumentProcessorServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert DocumentProcessorServiceClient._get_client_cert_source(None, False) is None - assert DocumentProcessorServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DocumentProcessorServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - 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_default_cert_source): - assert DocumentProcessorServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DocumentProcessorServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DocumentProcessorServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DocumentProcessorServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, default_universe, "always") == DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentProcessorServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DocumentProcessorServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentProcessorServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert DocumentProcessorServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DocumentProcessorServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DocumentProcessorServiceClient._get_universe_domain(None, None) == DocumentProcessorServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DocumentProcessorServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentProcessorServiceClient, "grpc"), - (DocumentProcessorServiceAsyncClient, "grpc_asyncio"), - (DocumentProcessorServiceClient, "rest"), -]) -def test_document_processor_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -def test_document_processor_service_client_get_transport_class(): - transport = DocumentProcessorServiceClient.get_transport_class() - available_transports = [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentProcessorServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentProcessorServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "true"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", "false"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "true"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - DocumentProcessorServiceClient, DocumentProcessorServiceAsyncClient -]) -@mock.patch.object(DocumentProcessorServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceClient)) -@mock.patch.object(DocumentProcessorServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentProcessorServiceAsyncClient)) -def test_document_processor_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DocumentProcessorServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentProcessorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc"), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest"), -]) -def test_document_processor_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceRestTransport, "rest", None), -]) -def test_document_processor_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_processor_types(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - response = client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - client.get_processor_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - -@pytest.mark.asyncio -async def test_get_processor_type_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorTypeRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - )) - response = await client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -@pytest.mark.asyncio -async def test_get_processor_type_async_from_dict(): - await test_get_processor_type_async(request_type=dict) - - -def test_get_processor_type_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = processor_type.ProcessorType() - client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_processor_type_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorTypeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - await client.get_processor_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_processor_type_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor_type( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_processor_type_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_type_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor_type.ProcessorType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor_type.ProcessorType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor_type( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_processor_type_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - client.list_processors() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - -@pytest.mark.asyncio -async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListProcessorsRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListProcessorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_processors_async_from_dict(): - await test_list_processors_async(request_type=dict) - - -def test_list_processors_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = document_processor_service.ListProcessorsResponse() - client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_processors_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListProcessorsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - await client.list_processors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_processors_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_processors( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_processors_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_processors_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListProcessorsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListProcessorsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_processors( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_processors_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_pager(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_processors(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) -def test_list_processors_pages(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = list(client.list_processors(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_processors_async_pager(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_processors(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, processor.Processor) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_processors_async_pages(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_processors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_processors(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - client.get_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - -@pytest.mark.asyncio -async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_get_processor_async_from_dict(): - await test_get_processor_async(request_type=dict) - - -def test_get_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = processor.Processor() - client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - await client.get_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_processor_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_processor_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_processor_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_processor_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.TrainProcessorVersionRequest, - dict, -]) -def test_train_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.TrainProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_train_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - client.train_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.TrainProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_train_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.TrainProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.TrainProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_train_processor_version_async_from_dict(): - await test_train_processor_version_async(request_type=dict) - - -def test_train_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.TrainProcessorVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_train_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.TrainProcessorVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.train_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_train_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.train_processor_version( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor_version - mock_val = processor.ProcessorVersion(name='name_value') - assert arg == mock_val - - -def test_train_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.train_processor_version( - document_processor_service.TrainProcessorVersionRequest(), - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_train_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.train_processor_version( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor_version - mock_val = processor.ProcessorVersion(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_train_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.train_processor_version( - document_processor_service.TrainProcessorVersionRequest(), - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - model_type=processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE, - ) - 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 - assert response.model_type == processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE - - -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, - model_type=processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE, - )) - 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 - assert response.model_type == processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE - - -@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 = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_processor_versions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - client.delete_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_delete_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_version_async_from_dict(): - await test_delete_processor_version_async(request_type=dict) - - -def test_delete_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_deploy_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - client.deploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_deploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeployProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_deploy_processor_version_async_from_dict(): - await test_deploy_processor_version_async(request_type=dict) - - -def test_deploy_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_deploy_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.deploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_deploy_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.deploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_deploy_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_deploy_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.deploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_deploy_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undeploy_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - client.undeploy_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.UndeployProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.UndeployProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undeploy_processor_version_async_from_dict(): - await test_undeploy_processor_version_async(request_type=dict) - - -def test_undeploy_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_undeploy_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.UndeployProcessorVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undeploy_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_undeploy_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.undeploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_undeploy_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_undeploy_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.undeploy_processor_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_undeploy_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - response = client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - client.create_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - -@pytest.mark.asyncio -async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.CreateProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - )) - response = await client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.CreateProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@pytest.mark.asyncio -async def test_create_processor_async_from_dict(): - await test_create_processor_async(request_type=dict) - - -def test_create_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = gcd_processor.Processor() - client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.CreateProcessorRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - await client.create_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_processor_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - - -def test_create_processor_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_processor_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_processor.Processor() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_processor.Processor()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_processor( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].processor - mock_val = gcd_processor.Processor(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_processor_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - client.delete_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - -@pytest.mark.asyncio -async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DeleteProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DeleteProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_processor_async_from_dict(): - await test_delete_processor_async(request_type=dict) - - -def test_delete_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DeleteProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_processor_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_processor_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_processor_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_processor( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_processor_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_enable_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - client.enable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - -@pytest.mark.asyncio -async def test_enable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EnableProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EnableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_enable_processor_async_from_dict(): - await test_enable_processor_async(request_type=dict) - - -def test_enable_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_enable_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EnableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.enable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_disable_processor_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - client.disable_processor() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - -@pytest.mark.asyncio -async def test_disable_processor_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.DisableProcessorRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.DisableProcessorRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_disable_processor_async_from_dict(): - await test_disable_processor_async(request_type=dict) - - -def test_disable_processor_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_disable_processor_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.DisableProcessorRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_processor), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.disable_processor(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_default_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - client.set_default_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_set_default_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.SetDefaultProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_default_processor_version_async_from_dict(): - await test_set_default_processor_version_async(request_type=dict) - - -def test_set_default_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor=processor_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.SetDefaultProcessorVersionRequest() - - request.processor = 'processor_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_default_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor=processor_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_review_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - client.review_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - -@pytest.mark.asyncio -async def test_review_document_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ReviewDocumentRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ReviewDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_review_document_async_from_dict(): - await test_review_document_async(request_type=dict) - - -def test_review_document_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_review_document_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ReviewDocumentRequest() - - request.human_review_config = 'human_review_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.review_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'human_review_config=human_review_config_value', - ) in kw['metadata'] - - -def test_review_document_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.review_document( - human_review_config='human_review_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - - -def test_review_document_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - -@pytest.mark.asyncio -async def test_review_document_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.review_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.review_document( - human_review_config='human_review_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].human_review_config - mock_val = 'human_review_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_review_document_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EvaluateProcessorVersionRequest, - dict, -]) -def test_evaluate_processor_version(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_evaluate_processor_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - client.evaluate_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_evaluate_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.EvaluateProcessorVersionRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_evaluate_processor_version_async_from_dict(): - await test_evaluate_processor_version_async(request_type=dict) - - -def test_evaluate_processor_version_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EvaluateProcessorVersionRequest() - - request.processor_version = 'processor_version_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor_version=processor_version_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_evaluate_processor_version_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.EvaluateProcessorVersionRequest() - - request.processor_version = 'processor_version_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.evaluate_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'processor_version=processor_version_value', - ) in kw['metadata'] - - -def test_evaluate_processor_version_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.evaluate_processor_version( - processor_version='processor_version_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].processor_version - mock_val = 'processor_version_value' - assert arg == mock_val - - -def test_evaluate_processor_version_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.evaluate_processor_version( - document_processor_service.EvaluateProcessorVersionRequest(), - processor_version='processor_version_value', - ) - -@pytest.mark.asyncio -async def test_evaluate_processor_version_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.evaluate_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.evaluate_processor_version( - processor_version='processor_version_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].processor_version - mock_val = 'processor_version_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_evaluate_processor_version_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.evaluate_processor_version( - document_processor_service.EvaluateProcessorVersionRequest(), - processor_version='processor_version_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetEvaluationRequest, - dict, -]) -def test_get_evaluation(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - ) - response = client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - - -def test_get_evaluation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - client.get_evaluation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetEvaluationRequest() - -@pytest.mark.asyncio -async def test_get_evaluation_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.GetEvaluationRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - )) - response = await client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.GetEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - - -@pytest.mark.asyncio -async def test_get_evaluation_async_from_dict(): - await test_get_evaluation_async(request_type=dict) - - -def test_get_evaluation_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetEvaluationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - call.return_value = evaluation.Evaluation() - client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_evaluation_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.GetEvaluationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation.Evaluation()) - await client.get_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_evaluation_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation.Evaluation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_evaluation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_evaluation_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_evaluation( - document_processor_service.GetEvaluationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_evaluation_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation.Evaluation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation.Evaluation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_evaluation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_evaluation_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_evaluation( - document_processor_service.GetEvaluationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListEvaluationsRequest, - dict, -]) -def test_list_evaluations(request_type, transport: str = 'grpc'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_evaluations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - client.list_evaluations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListEvaluationsRequest() - -@pytest.mark.asyncio -async def test_list_evaluations_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ListEvaluationsRequest): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ListEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_evaluations_async_from_dict(): - await test_list_evaluations_async(request_type=dict) - - -def test_list_evaluations_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListEvaluationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - call.return_value = document_processor_service.ListEvaluationsResponse() - client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_evaluations_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_processor_service.ListEvaluationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListEvaluationsResponse()) - await client.list_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_evaluations_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListEvaluationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_evaluations( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_evaluations_flattened_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_evaluations( - document_processor_service.ListEvaluationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_evaluations_flattened_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_processor_service.ListEvaluationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_processor_service.ListEvaluationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_evaluations( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_evaluations_flattened_error_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_evaluations( - document_processor_service.ListEvaluationsRequest(), - parent='parent_value', - ) - - -def test_list_evaluations_pager(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_evaluations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in results) -def test_list_evaluations_pages(transport_name: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_evaluations(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_evaluations_async_pager(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_evaluations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_evaluations_async_pages(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_evaluations(request={}) - ).pages: - 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.ImportProcessorVersionRequest, - dict, -]) -def test_import_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.import_processor_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_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.ImportProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_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.import_processor_version), - '__call__') as call: - client.import_processor_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_processor_service.ImportProcessorVersionRequest() - -@pytest.mark.asyncio -async def test_import_processor_version_async(transport: str = 'grpc_asyncio', request_type=document_processor_service.ImportProcessorVersionRequest): - 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.import_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.import_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.ImportProcessorVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_processor_version_async_from_dict(): - await test_import_processor_version_async(request_type=dict) - - -def test_import_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.ImportProcessorVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_processor_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_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.ImportProcessorVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_processor_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_processor_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_import_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.import_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.import_processor_version( - 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_import_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.import_processor_version( - document_processor_service.ImportProcessorVersionRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_import_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.import_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.import_processor_version( - 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_import_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.import_processor_version( - document_processor_service.ImportProcessorVersionRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ProcessRequest, - dict, -]) -def test_process_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse( - human_review_operation='human_review_operation_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.process_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.ProcessResponse) - assert response.human_review_operation == 'human_review_operation_value' - - -def test_process_document_rest_required_fields(request_type=document_processor_service.ProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).process_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.process_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_process_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.process_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_process_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_process_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_process_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ProcessRequest.pb(document_processor_service.ProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ProcessResponse.to_json(document_processor_service.ProcessResponse()) - - request = document_processor_service.ProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ProcessResponse() - - client.process_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_process_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.process_document(request) - - -def test_process_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ProcessResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ProcessResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.process_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}:process" % client.transport._host, args[1]) - - -def test_process_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.process_document( - document_processor_service.ProcessRequest(), - name='name_value', - ) - - -def test_process_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.BatchProcessRequest, - dict, -]) -def test_batch_process_documents_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_process_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_process_documents_rest_required_fields(request_type=document_processor_service.BatchProcessRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_process_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_process_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_process_documents_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_process_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_process_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_batch_process_documents") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_batch_process_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.BatchProcessRequest.pb(document_processor_service.BatchProcessRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.BatchProcessRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_process_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_process_documents_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.BatchProcessRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_process_documents(request) - - -def test_batch_process_documents_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_process_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}:batchProcess" % client.transport._host, args[1]) - - -def test_batch_process_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_process_documents( - document_processor_service.BatchProcessRequest(), - name='name_value', - ) - - -def test_batch_process_documents_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.FetchProcessorTypesRequest, - dict, -]) -def test_fetch_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.fetch_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_processor_service.FetchProcessorTypesResponse) - - -def test_fetch_processor_types_rest_required_fields(request_type=document_processor_service.FetchProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.fetch_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_fetch_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_fetch_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.FetchProcessorTypesRequest.pb(document_processor_service.FetchProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.FetchProcessorTypesResponse.to_json(document_processor_service.FetchProcessorTypesResponse()) - - request = document_processor_service.FetchProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.FetchProcessorTypesResponse() - - client.fetch_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.FetchProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_processor_types(request) - - -def test_fetch_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.FetchProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.FetchProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.fetch_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}:fetchProcessorTypes" % client.transport._host, args[1]) - - -def test_fetch_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.fetch_processor_types( - document_processor_service.FetchProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_fetch_processor_types_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorTypesRequest, - dict, -]) -def test_list_processor_types_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_types_rest_required_fields(request_type=document_processor_service.ListProcessorTypesRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_types_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_types_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_types") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorTypesRequest.pb(document_processor_service.ListProcessorTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorTypesResponse.to_json(document_processor_service.ListProcessorTypesResponse()) - - request = document_processor_service.ListProcessorTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorTypesResponse() - - client.list_processor_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_types_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorTypesRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_types(request) - - -def test_list_processor_types_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processorTypes" % client.transport._host, args[1]) - - -def test_list_processor_types_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_types( - document_processor_service.ListProcessorTypesRequest(), - parent='parent_value', - ) - - -def test_list_processor_types_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[], - next_page_token='def', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorTypesResponse( - processor_types=[ - processor_type.ProcessorType(), - processor_type.ProcessorType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processor_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor_type.ProcessorType) - for i in results) - - pages = list(client.list_processor_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorTypeRequest, - dict, -]) -def test_get_processor_type_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType( - name='name_value', - type_='type__value', - category='category_value', - allow_creation=True, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - sample_document_uris=['sample_document_uris_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_type(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor_type.ProcessorType) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.category == 'category_value' - assert response.allow_creation is True - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.sample_document_uris == ['sample_document_uris_value'] - - -def test_get_processor_type_rest_required_fields(request_type=document_processor_service.GetProcessorTypeRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_type_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_type_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_type") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorTypeRequest.pb(document_processor_service.GetProcessorTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor_type.ProcessorType.to_json(processor_type.ProcessorType()) - - request = document_processor_service.GetProcessorTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor_type.ProcessorType() - - client.get_processor_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_type_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorTypeRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_type(request) - - -def test_get_processor_type_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor_type.ProcessorType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processorTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor_type.ProcessorType.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processorTypes/*}" % client.transport._host, args[1]) - - -def test_get_processor_type_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_type( - document_processor_service.GetProcessorTypeRequest(), - name='name_value', - ) - - -def test_get_processor_type_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorsRequest, - dict, -]) -def test_list_processors_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processors(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processors_rest_required_fields(request_type=document_processor_service.ListProcessorsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processors(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processors_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processors._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processors_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processors") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processors") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorsRequest.pb(document_processor_service.ListProcessorsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorsResponse.to_json(document_processor_service.ListProcessorsResponse()) - - request = document_processor_service.ListProcessorsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorsResponse() - - client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processors(request) - - -def test_list_processors_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processors(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_list_processors_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processors( - document_processor_service.ListProcessorsRequest(), - parent='parent_value', - ) - - -def test_list_processors_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - processor.Processor(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorsResponse( - processors=[], - next_page_token='def', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorsResponse( - processors=[ - processor.Processor(), - processor.Processor(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_processors(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.Processor) - for i in results) - - pages = list(client.list_processors(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorRequest, - dict, -]) -def test_get_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_get_processor_rest_required_fields(request_type=document_processor_service.GetProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorRequest.pb(document_processor_service.GetProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.Processor.to_json(processor.Processor()) - - request = document_processor_service.GetProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.Processor() - - client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor(request) - - -def test_get_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_get_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor( - document_processor_service.GetProcessorRequest(), - name='name_value', - ) - - -def test_get_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.TrainProcessorVersionRequest, - dict, -]) -def test_train_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.train_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_train_processor_version_rest_required_fields(request_type=document_processor_service.TrainProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.train_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_train_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.train_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_train_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_train_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_train_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.TrainProcessorVersionRequest.pb(document_processor_service.TrainProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.TrainProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.train_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_train_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.TrainProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.train_processor_version(request) - - -def test_train_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.train_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:train" % client.transport._host, args[1]) - - -def test_train_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.train_processor_version( - document_processor_service.TrainProcessorVersionRequest(), - parent='parent_value', - processor_version=processor.ProcessorVersion(name='name_value'), - ) - - -def test_train_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetProcessorVersionRequest, - dict, -]) -def test_get_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion( - name='name_value', - display_name='display_name_value', - state=processor.ProcessorVersion.State.DEPLOYED, - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - google_managed=True, - model_type=processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_processor_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, processor.ProcessorVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == processor.ProcessorVersion.State.DEPLOYED - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - assert response.google_managed is True - assert response.model_type == processor.ProcessorVersion.ModelType.MODEL_TYPE_GENERATIVE - - -def test_get_processor_version_rest_required_fields(request_type=document_processor_service.GetProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetProcessorVersionRequest.pb(document_processor_service.GetProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = processor.ProcessorVersion.to_json(processor.ProcessorVersion()) - - request = document_processor_service.GetProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = processor.ProcessorVersion() - - client.get_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_processor_version(request) - - -def test_get_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = processor.ProcessorVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = processor.ProcessorVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_get_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_processor_version( - document_processor_service.GetProcessorVersionRequest(), - name='name_value', - ) - - -def test_get_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListProcessorVersionsRequest, - dict, -]) -def test_list_processor_versions_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_processor_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProcessorVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_processor_versions_rest_required_fields(request_type=document_processor_service.ListProcessorVersionsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processor_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_processor_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_processor_versions_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_processor_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_processor_versions_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_processor_versions") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_processor_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListProcessorVersionsRequest.pb(document_processor_service.ListProcessorVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListProcessorVersionsResponse.to_json(document_processor_service.ListProcessorVersionsResponse()) - - request = document_processor_service.ListProcessorVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListProcessorVersionsResponse() - - client.list_processor_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_processor_versions_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListProcessorVersionsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_processor_versions(request) - - -def test_list_processor_versions_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListProcessorVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListProcessorVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_processor_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions" % client.transport._host, args[1]) - - -def test_list_processor_versions_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_processor_versions( - document_processor_service.ListProcessorVersionsRequest(), - parent='parent_value', - ) - - -def test_list_processor_versions_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - next_page_token='abc', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[], - next_page_token='def', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - ], - next_page_token='ghi', - ), - document_processor_service.ListProcessorVersionsResponse( - processor_versions=[ - processor.ProcessorVersion(), - processor.ProcessorVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListProcessorVersionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - pager = client.list_processor_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, processor.ProcessorVersion) - for i in results) - - pages = list(client.list_processor_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorVersionRequest, - dict, -]) -def test_delete_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_version_rest_required_fields(request_type=document_processor_service.DeleteProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorVersionRequest.pb(document_processor_service.DeleteProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor_version(request) - - -def test_delete_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}" % client.transport._host, args[1]) - - -def test_delete_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor_version( - document_processor_service.DeleteProcessorVersionRequest(), - name='name_value', - ) - - -def test_delete_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeployProcessorVersionRequest, - dict, -]) -def test_deploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.deploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_deploy_processor_version_rest_required_fields(request_type=document_processor_service.DeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.deploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_deploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.deploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_deploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_deploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_deploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeployProcessorVersionRequest.pb(document_processor_service.DeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.deploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_deploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.deploy_processor_version(request) - - -def test_deploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.deploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:deploy" % client.transport._host, args[1]) - - -def test_deploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.deploy_processor_version( - document_processor_service.DeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_deploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.UndeployProcessorVersionRequest, - dict, -]) -def test_undeploy_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.undeploy_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_undeploy_processor_version_rest_required_fields(request_type=document_processor_service.UndeployProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.undeploy_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undeploy_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undeploy_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undeploy_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_undeploy_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_undeploy_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.UndeployProcessorVersionRequest.pb(document_processor_service.UndeployProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.UndeployProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undeploy_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undeploy_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.UndeployProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.undeploy_processor_version(request) - - -def test_undeploy_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.undeploy_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*}:undeploy" % client.transport._host, args[1]) - - -def test_undeploy_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undeploy_processor_version( - document_processor_service.UndeployProcessorVersionRequest(), - name='name_value', - ) - - -def test_undeploy_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.CreateProcessorRequest, - dict, -]) -def test_create_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["processor"] = {'name': 'name_value', 'type_': 'type__value', 'display_name': 'display_name_value', 'state': 1, 'default_processor_version': 'default_processor_version_value', 'processor_version_aliases': [{'alias': 'alias_value', 'processor_version': 'processor_version_value'}], 'process_endpoint': 'process_endpoint_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'kms_key_name': 'kms_key_name_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = document_processor_service.CreateProcessorRequest.meta.fields["processor"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["processor"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["processor"][field])): - del request_init["processor"][field][i][subfield] - else: - del request_init["processor"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor( - name='name_value', - type_='type__value', - display_name='display_name_value', - state=gcd_processor.Processor.State.ENABLED, - default_processor_version='default_processor_version_value', - process_endpoint='process_endpoint_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_processor(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_processor.Processor) - assert response.name == 'name_value' - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.state == gcd_processor.Processor.State.ENABLED - assert response.default_processor_version == 'default_processor_version_value' - assert response.process_endpoint == 'process_endpoint_value' - assert response.kms_key_name == 'kms_key_name_value' - - -def test_create_processor_rest_required_fields(request_type=document_processor_service.CreateProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "processor", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_create_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_create_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.CreateProcessorRequest.pb(document_processor_service.CreateProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_processor.Processor.to_json(gcd_processor.Processor()) - - request = document_processor_service.CreateProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_processor.Processor() - - client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.CreateProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_processor(request) - - -def test_create_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_processor.Processor() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcd_processor.Processor.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) - - -def test_create_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_processor( - document_processor_service.CreateProcessorRequest(), - parent='parent_value', - processor=gcd_processor.Processor(name='name_value'), - ) - - -def test_create_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DeleteProcessorRequest, - dict, -]) -def test_delete_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_processor_rest_required_fields(request_type=document_processor_service.DeleteProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_delete_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_delete_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DeleteProcessorRequest.pb(document_processor_service.DeleteProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DeleteProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DeleteProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_processor(request) - - -def test_delete_processor_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_processor(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) - - -def test_delete_processor_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_processor( - document_processor_service.DeleteProcessorRequest(), - name='name_value', - ) - - -def test_delete_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EnableProcessorRequest, - dict, -]) -def test_enable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.enable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_enable_processor_rest_required_fields(request_type=document_processor_service.EnableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).enable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.enable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_enable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.enable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_enable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_enable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EnableProcessorRequest.pb(document_processor_service.EnableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EnableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.enable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_enable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EnableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.enable_processor(request) - - -def test_enable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.DisableProcessorRequest, - dict, -]) -def test_disable_processor_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.disable_processor(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_disable_processor_rest_required_fields(request_type=document_processor_service.DisableProcessorRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).disable_processor._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.disable_processor(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_disable_processor_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.disable_processor._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_processor_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_disable_processor") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_disable_processor") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.DisableProcessorRequest.pb(document_processor_service.DisableProcessorRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.DisableProcessorRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.disable_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_disable_processor_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.DisableProcessorRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.disable_processor(request) - - -def test_disable_processor_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.SetDefaultProcessorVersionRequest, - dict, -]) -def test_set_default_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_default_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_default_processor_version_rest_required_fields(request_type=document_processor_service.SetDefaultProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor"] = "" - request_init["default_processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processor"] = 'processor_value' - jsonified_request["defaultProcessorVersion"] = 'default_processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_default_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processor" in jsonified_request - assert jsonified_request["processor"] == 'processor_value' - assert "defaultProcessorVersion" in jsonified_request - assert jsonified_request["defaultProcessorVersion"] == 'default_processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_default_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_default_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_default_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processor", "defaultProcessorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_set_default_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_set_default_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.SetDefaultProcessorVersionRequest.pb(document_processor_service.SetDefaultProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.SetDefaultProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_default_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_default_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.SetDefaultProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_default_processor_version(request) - - -def test_set_default_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ReviewDocumentRequest, - dict, -]) -def test_review_document_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.review_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_review_document_rest_required_fields(request_type=document_processor_service.ReviewDocumentRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["human_review_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["humanReviewConfig"] = 'human_review_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).review_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "humanReviewConfig" in jsonified_request - assert jsonified_request["humanReviewConfig"] == 'human_review_config_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.review_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_review_document_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.review_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("humanReviewConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_review_document_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_review_document") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_review_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ReviewDocumentRequest.pb(document_processor_service.ReviewDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.ReviewDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.review_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_review_document_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ReviewDocumentRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.review_document(request) - - -def test_review_document_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'human_review_config': 'projects/sample1/locations/sample2/processors/sample3/humanReviewConfig'} - - # get truthy value for each flattened field - mock_args = dict( - human_review_config='human_review_config_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.review_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{human_review_config=projects/*/locations/*/processors/*/humanReviewConfig}:reviewDocument" % client.transport._host, args[1]) - - -def test_review_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.review_document( - document_processor_service.ReviewDocumentRequest(), - human_review_config='human_review_config_value', - ) - - -def test_review_document_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.EvaluateProcessorVersionRequest, - dict, -]) -def test_evaluate_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.evaluate_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_evaluate_processor_version_rest_required_fields(request_type=document_processor_service.EvaluateProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["processor_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["processorVersion"] = 'processor_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).evaluate_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "processorVersion" in jsonified_request - assert jsonified_request["processorVersion"] == 'processor_version_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.evaluate_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_evaluate_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.evaluate_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("processorVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_evaluate_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_evaluate_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_evaluate_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.EvaluateProcessorVersionRequest.pb(document_processor_service.EvaluateProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.EvaluateProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.evaluate_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_evaluate_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.EvaluateProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.evaluate_processor_version(request) - - -def test_evaluate_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'processor_version': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - processor_version='processor_version_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.evaluate_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{processor_version=projects/*/locations/*/processors/*/processorVersions/*}:evaluateProcessorVersion" % client.transport._host, args[1]) - - -def test_evaluate_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.evaluate_processor_version( - document_processor_service.EvaluateProcessorVersionRequest(), - processor_version='processor_version_value', - ) - - -def test_evaluate_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.GetEvaluationRequest, - dict, -]) -def test_get_evaluation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation( - name='name_value', - kms_key_name='kms_key_name_value', - kms_key_version_name='kms_key_version_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_evaluation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.kms_key_version_name == 'kms_key_version_name_value' - - -def test_get_evaluation_rest_required_fields(request_type=document_processor_service.GetEvaluationRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_evaluation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_evaluation_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_evaluation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_evaluation_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_get_evaluation") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_get_evaluation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.GetEvaluationRequest.pb(document_processor_service.GetEvaluationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = evaluation.Evaluation.to_json(evaluation.Evaluation()) - - request = document_processor_service.GetEvaluationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = evaluation.Evaluation() - - client.get_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_evaluation_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.GetEvaluationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_evaluation(request) - - -def test_get_evaluation_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = evaluation.Evaluation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4/evaluations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = evaluation.Evaluation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_evaluation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/processorVersions/*/evaluations/*}" % client.transport._host, args[1]) - - -def test_get_evaluation_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_evaluation( - document_processor_service.GetEvaluationRequest(), - name='name_value', - ) - - -def test_get_evaluation_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ListEvaluationsRequest, - dict, -]) -def test_list_evaluations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_evaluations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_evaluations_rest_required_fields(request_type=document_processor_service.ListEvaluationsRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_evaluations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_evaluations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_evaluations_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_evaluations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_evaluations_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_list_evaluations") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_list_evaluations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ListEvaluationsRequest.pb(document_processor_service.ListEvaluationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_processor_service.ListEvaluationsResponse.to_json(document_processor_service.ListEvaluationsResponse()) - - request = document_processor_service.ListEvaluationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_processor_service.ListEvaluationsResponse() - - client.list_evaluations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_evaluations_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ListEvaluationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_evaluations(request) - - -def test_list_evaluations_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_processor_service.ListEvaluationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_processor_service.ListEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_evaluations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*/processorVersions/*}/evaluations" % client.transport._host, args[1]) - - -def test_list_evaluations_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_evaluations( - document_processor_service.ListEvaluationsRequest(), - parent='parent_value', - ) - - -def test_list_evaluations_rest_pager(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - document_processor_service.ListEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_processor_service.ListEvaluationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3/processorVersions/sample4'} - - pager = client.list_evaluations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in results) - - pages = list(client.list_evaluations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_processor_service.ImportProcessorVersionRequest, - dict, -]) -def test_import_processor_version_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_processor_version(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_processor_version_rest_required_fields(request_type=document_processor_service.ImportProcessorVersionRequest): - transport_class = transports.DocumentProcessorServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_processor_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_processor_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_processor_version_rest_unset_required_fields(): - transport = transports.DocumentProcessorServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_processor_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_processor_version_rest_interceptors(null_interceptor): - transport = transports.DocumentProcessorServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentProcessorServiceRestInterceptor(), - ) - client = DocumentProcessorServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "post_import_processor_version") as post, \ - mock.patch.object(transports.DocumentProcessorServiceRestInterceptor, "pre_import_processor_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_processor_service.ImportProcessorVersionRequest.pb(document_processor_service.ImportProcessorVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_processor_service.ImportProcessorVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_processor_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_processor_version_rest_bad_request(transport: str = 'rest', request_type=document_processor_service.ImportProcessorVersionRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_processor_version(request) - - -def test_import_processor_version_rest_flattened(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/processors/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.import_processor_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{parent=projects/*/locations/*/processors/*}/processorVersions:importProcessorVersion" % client.transport._host, args[1]) - - -def test_import_processor_version_rest_flattened_error(transport: str = 'rest'): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.import_processor_version( - document_processor_service.ImportProcessorVersionRequest(), - parent='parent_value', - ) - - -def test_import_processor_version_rest_error(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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 = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentProcessorServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentProcessorServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentProcessorServiceGrpcTransport, - ) - -def test_document_processor_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_processor_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentProcessorServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'process_document', - 'batch_process_documents', - 'fetch_processor_types', - 'list_processor_types', - 'get_processor_type', - 'list_processors', - 'get_processor', - 'train_processor_version', - 'get_processor_version', - 'list_processor_versions', - 'delete_processor_version', - 'deploy_processor_version', - 'undeploy_processor_version', - 'create_processor', - 'delete_processor', - 'enable_processor', - 'disable_processor', - 'set_default_processor_version', - 'review_document', - 'evaluate_processor_version', - 'get_evaluation', - 'list_evaluations', - 'import_processor_version', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_document_processor_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_document_processor_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.documentai_v1beta3.services.document_processor_service.transports.DocumentProcessorServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentProcessorServiceTransport() - adc.assert_called_once() - - -def test_document_processor_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentProcessorServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - ], -) -def test_document_processor_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentProcessorServiceGrpcTransport, - transports.DocumentProcessorServiceGrpcAsyncIOTransport, - transports.DocumentProcessorServiceRestTransport, - ], -) -def test_document_processor_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentProcessorServiceGrpcTransport, grpc_helpers), - (transports.DocumentProcessorServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_processor_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "documentai.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="documentai.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_document_processor_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DocumentProcessorServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_processor_service_rest_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_no_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_processor_service_host_with_port(transport_name): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_processor_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentProcessorServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentProcessorServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.process_document._session - session2 = client2.transport.process_document._session - assert session1 != session2 - session1 = client1.transport.batch_process_documents._session - session2 = client2.transport.batch_process_documents._session - assert session1 != session2 - session1 = client1.transport.fetch_processor_types._session - session2 = client2.transport.fetch_processor_types._session - assert session1 != session2 - session1 = client1.transport.list_processor_types._session - session2 = client2.transport.list_processor_types._session - assert session1 != session2 - session1 = client1.transport.get_processor_type._session - session2 = client2.transport.get_processor_type._session - assert session1 != session2 - session1 = client1.transport.list_processors._session - session2 = client2.transport.list_processors._session - assert session1 != session2 - session1 = client1.transport.get_processor._session - session2 = client2.transport.get_processor._session - assert session1 != session2 - session1 = client1.transport.train_processor_version._session - session2 = client2.transport.train_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_processor_version._session - session2 = client2.transport.get_processor_version._session - assert session1 != session2 - session1 = client1.transport.list_processor_versions._session - session2 = client2.transport.list_processor_versions._session - assert session1 != session2 - session1 = client1.transport.delete_processor_version._session - session2 = client2.transport.delete_processor_version._session - assert session1 != session2 - session1 = client1.transport.deploy_processor_version._session - session2 = client2.transport.deploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.undeploy_processor_version._session - session2 = client2.transport.undeploy_processor_version._session - assert session1 != session2 - session1 = client1.transport.create_processor._session - session2 = client2.transport.create_processor._session - assert session1 != session2 - session1 = client1.transport.delete_processor._session - session2 = client2.transport.delete_processor._session - assert session1 != session2 - session1 = client1.transport.enable_processor._session - session2 = client2.transport.enable_processor._session - assert session1 != session2 - session1 = client1.transport.disable_processor._session - session2 = client2.transport.disable_processor._session - assert session1 != session2 - session1 = client1.transport.set_default_processor_version._session - session2 = client2.transport.set_default_processor_version._session - assert session1 != session2 - session1 = client1.transport.review_document._session - session2 = client2.transport.review_document._session - assert session1 != session2 - session1 = client1.transport.evaluate_processor_version._session - session2 = client2.transport.evaluate_processor_version._session - assert session1 != session2 - session1 = client1.transport.get_evaluation._session - session2 = client2.transport.get_evaluation._session - assert session1 != session2 - session1 = client1.transport.list_evaluations._session - session2 = client2.transport.list_evaluations._session - assert session1 != session2 - session1 = client1.transport.import_processor_version._session - session2 = client2.transport.import_processor_version._session - assert session1 != session2 -def test_document_processor_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_document_processor_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentProcessorServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentProcessorServiceGrpcTransport, transports.DocumentProcessorServiceGrpcAsyncIOTransport]) -def test_document_processor_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_document_processor_service_grpc_lro_client(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_document_processor_service_grpc_lro_async_client(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_evaluation_path(): - project = "squid" - location = "clam" - processor = "whelk" - processor_version = "octopus" - evaluation = "oyster" - expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}".format(project=project, location=location, processor=processor, processor_version=processor_version, evaluation=evaluation, ) - actual = DocumentProcessorServiceClient.evaluation_path(project, location, processor, processor_version, evaluation) - assert expected == actual - - -def test_parse_evaluation_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "processor": "mussel", - "processor_version": "winkle", - "evaluation": "nautilus", - } - path = DocumentProcessorServiceClient.evaluation_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_evaluation_path(path) - assert expected == actual - -def test_human_review_config_path(): - project = "scallop" - location = "abalone" - processor = "squid" - expected = "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format(project=project, location=location, processor=processor, ) - actual = DocumentProcessorServiceClient.human_review_config_path(project, location, processor) - assert expected == actual - - -def test_parse_human_review_config_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor": "octopus", - } - path = DocumentProcessorServiceClient.human_review_config_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_human_review_config_path(path) - assert expected == actual - -def test_processor_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) - actual = DocumentProcessorServiceClient.processor_path(project, location, processor) - assert expected == actual - - -def test_parse_processor_path(): - expected = { - "project": "mussel", - "location": "winkle", - "processor": "nautilus", - } - path = DocumentProcessorServiceClient.processor_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_path(path) - assert expected == actual - -def test_processor_type_path(): - project = "scallop" - location = "abalone" - processor_type = "squid" - expected = "projects/{project}/locations/{location}/processorTypes/{processor_type}".format(project=project, location=location, processor_type=processor_type, ) - actual = DocumentProcessorServiceClient.processor_type_path(project, location, processor_type) - assert expected == actual - - -def test_parse_processor_type_path(): - expected = { - "project": "clam", - "location": "whelk", - "processor_type": "octopus", - } - path = DocumentProcessorServiceClient.processor_type_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_type_path(path) - assert expected == actual - -def test_processor_version_path(): - project = "oyster" - location = "nudibranch" - processor = "cuttlefish" - processor_version = "mussel" - expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format(project=project, location=location, processor=processor, processor_version=processor_version, ) - actual = DocumentProcessorServiceClient.processor_version_path(project, location, processor, processor_version) - assert expected == actual - - -def test_parse_processor_version_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "processor": "scallop", - "processor_version": "abalone", - } - path = DocumentProcessorServiceClient.processor_version_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_processor_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentProcessorServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DocumentProcessorServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentProcessorServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DocumentProcessorServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentProcessorServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DocumentProcessorServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DocumentProcessorServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DocumentProcessorServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentProcessorServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DocumentProcessorServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentProcessorServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentProcessorServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentProcessorServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_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 = 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_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 = 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_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 = 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_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.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = DocumentProcessorServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (DocumentProcessorServiceClient, transports.DocumentProcessorServiceGrpcTransport), - (DocumentProcessorServiceAsyncClient, transports.DocumentProcessorServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_service.py b/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_service.py deleted file mode 100644 index 6f105174af04..000000000000 --- a/owl-bot-staging/google-cloud-documentai/v1beta3/tests/unit/gapic/documentai_v1beta3/test_document_service.py +++ /dev/null @@ -1,6093 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_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_service import DocumentServiceAsyncClient -from google.cloud.documentai_v1beta3.services.document_service import DocumentServiceClient -from google.cloud.documentai_v1beta3.services.document_service import pagers -from google.cloud.documentai_v1beta3.services.document_service import transports -from google.cloud.documentai_v1beta3.types import dataset -from google.cloud.documentai_v1beta3.types import dataset as gcd_dataset -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_schema -from google.cloud.documentai_v1beta3.types import document_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 DocumentServiceClient._get_default_mtls_endpoint(None) is None - assert DocumentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert DocumentServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DocumentServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DocumentServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DocumentServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert DocumentServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DocumentServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DocumentServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert DocumentServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert DocumentServiceClient._get_client_cert_source(None, False) is None - assert DocumentServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DocumentServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - 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_default_cert_source): - assert DocumentServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DocumentServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DocumentServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DocumentServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DocumentServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DocumentServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DocumentServiceClient._get_api_endpoint(None, None, default_universe, "always") == DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - assert DocumentServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DocumentServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DocumentServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert DocumentServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DocumentServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DocumentServiceClient._get_universe_domain(None, None) == DocumentServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DocumentServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentServiceGrpcTransport, "grpc"), - (transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://documentai.googleapis.com' - ) - - -def test_document_service_client_get_transport_class(): - transport = DocumentServiceClient.get_transport_class() - available_transports = [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceAsyncClient)) -def test_document_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(DocumentServiceClient, '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(DocumentServiceClient, '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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "true"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "false"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "true"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_document_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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", [ - DocumentServiceClient, DocumentServiceAsyncClient -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -def test_document_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 - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - DocumentServiceClient, DocumentServiceAsyncClient -]) -@mock.patch.object(DocumentServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DocumentServiceAsyncClient)) -def test_document_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DocumentServiceClient._DEFAULT_UNIVERSE - default_endpoint = DocumentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DocumentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", None), -]) -def test_document_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_service_client_client_options_from_dict(): - with mock.patch('google.cloud.documentai_v1beta3.services.document_service.transports.DocumentServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_service.UpdateDatasetRequest, - dict, -]) -def test_update_dataset(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_dataset(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_service.UpdateDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_dataset_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 = DocumentServiceClient( - 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.update_dataset), - '__call__') as call: - client.update_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDatasetRequest() - -@pytest.mark.asyncio -async def test_update_dataset_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDatasetRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset), - '__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.update_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_dataset_async_from_dict(): - await test_update_dataset_async(request_type=dict) - - -def test_update_dataset_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDatasetRequest() - - request.dataset.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_dataset(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', - 'dataset.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_dataset_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDatasetRequest() - - request.dataset.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_dataset(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', - 'dataset.name=name_value', - ) in kw['metadata'] - - -def test_update_dataset_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset), - '__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.update_dataset( - dataset=gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].dataset - mock_val = gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_dataset_flattened_error(): - client = DocumentServiceClient( - 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.update_dataset( - document_service.UpdateDatasetRequest(), - dataset=gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_dataset_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset), - '__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.update_dataset( - dataset=gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].dataset - mock_val = gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_dataset_flattened_error_async(): - client = DocumentServiceAsyncClient( - 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.update_dataset( - document_service.UpdateDatasetRequest(), - dataset=gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ImportDocumentsRequest, - dict, -]) -def test_import_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_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_service.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_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 = DocumentServiceClient( - 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.import_documents), - '__call__') as call: - client.import_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ImportDocumentsRequest() - -@pytest.mark.asyncio -async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ImportDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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.import_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_service.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_documents_async_from_dict(): - await test_import_documents_async(request_type=dict) - - -def test_import_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ImportDocumentsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ImportDocumentsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -def test_import_documents_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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.import_documents( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - - -def test_import_documents_flattened_error(): - client = DocumentServiceClient( - 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.import_documents( - document_service.ImportDocumentsRequest(), - dataset='dataset_value', - ) - -@pytest.mark.asyncio -async def test_import_documents_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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.import_documents( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_import_documents_flattened_error_async(): - client = DocumentServiceAsyncClient( - 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.import_documents( - document_service.ImportDocumentsRequest(), - dataset='dataset_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.GetDocumentResponse( - ) - response = client.get_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_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_service.GetDocumentResponse) - - -def test_get_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 = DocumentServiceClient( - 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_document), - '__call__') as call: - client.get_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - -@pytest.mark.asyncio -async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.GetDocumentResponse( - )) - response = await client.get_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_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document_service.GetDocumentResponse) - - -@pytest.mark.asyncio -async def test_get_document_async_from_dict(): - await test_get_document_async(request_type=dict) - - -def test_get_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = document_service.GetDocumentResponse() - client.get_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.GetDocumentResponse()) - await client.get_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -def test_get_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.GetDocumentResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_document( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - - -def test_get_document_flattened_error(): - client = DocumentServiceClient( - 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_document( - document_service.GetDocumentRequest(), - dataset='dataset_value', - ) - -@pytest.mark.asyncio -async def test_get_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.GetDocumentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.GetDocumentResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_document( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - 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_document( - document_service.GetDocumentRequest(), - dataset='dataset_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_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_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_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 = DocumentServiceClient( - 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_documents), - '__call__') as call: - client.list_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - -@pytest.mark.asyncio -async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_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_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_documents_async_from_dict(): - await test_list_documents_async(request_type=dict) - - -def test_list_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = document_service.ListDocumentsResponse() - client.list_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - await client.list_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -def test_list_documents_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_documents( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - - -def test_list_documents_flattened_error(): - client = DocumentServiceClient( - 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_documents( - document_service.ListDocumentsRequest(), - dataset='dataset_value', - ) - -@pytest.mark.asyncio -async def test_list_documents_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_documents( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_documents_flattened_error_async(): - client = DocumentServiceAsyncClient( - 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_documents( - document_service.ListDocumentsRequest(), - dataset='dataset_value', - ) - - -def test_list_documents_pager(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - document_metadata=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('dataset', ''), - )), - ) - pager = client.list_documents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document_service.DocumentMetadata) - for i in results) -def test_list_documents_pages(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - document_metadata=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - ), - RuntimeError, - ) - pages = list(client.list_documents(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_documents_async_pager(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - document_metadata=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_documents(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, document_service.DocumentMetadata) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_documents_async_pages(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - document_metadata=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_documents(request={}) - ).pages: - 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_service.BatchDeleteDocumentsRequest, - dict, -]) -def test_batch_delete_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delete_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_delete_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_service.BatchDeleteDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_delete_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 = DocumentServiceClient( - 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_delete_documents), - '__call__') as call: - client.batch_delete_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.BatchDeleteDocumentsRequest() - -@pytest.mark.asyncio -async def test_batch_delete_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.BatchDeleteDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delete_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_delete_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_service.BatchDeleteDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_delete_documents_async_from_dict(): - await test_batch_delete_documents_async(request_type=dict) - - -def test_batch_delete_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.BatchDeleteDocumentsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_delete_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_batch_delete_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.BatchDeleteDocumentsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_delete_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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -def test_batch_delete_documents_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_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_delete_documents( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - - -def test_batch_delete_documents_flattened_error(): - client = DocumentServiceClient( - 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_delete_documents( - document_service.BatchDeleteDocumentsRequest(), - dataset='dataset_value', - ) - -@pytest.mark.asyncio -async def test_batch_delete_documents_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_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_delete_documents( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_delete_documents_flattened_error_async(): - client = DocumentServiceAsyncClient( - 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_delete_documents( - document_service.BatchDeleteDocumentsRequest(), - dataset='dataset_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDatasetSchemaRequest, - dict, -]) -def test_get_dataset_schema(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DatasetSchema( - name='name_value', - ) - response = client.get_dataset_schema(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_service.GetDatasetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DatasetSchema) - assert response.name == 'name_value' - - -def test_get_dataset_schema_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 = DocumentServiceClient( - 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_dataset_schema), - '__call__') as call: - client.get_dataset_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDatasetSchemaRequest() - -@pytest.mark.asyncio -async def test_get_dataset_schema_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDatasetSchemaRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.DatasetSchema( - name='name_value', - )) - response = await client.get_dataset_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDatasetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DatasetSchema) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_dataset_schema_async_from_dict(): - await test_get_dataset_schema_async(request_type=dict) - - -def test_get_dataset_schema_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDatasetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset_schema), - '__call__') as call: - call.return_value = dataset.DatasetSchema() - client.get_dataset_schema(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_dataset_schema_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDatasetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DatasetSchema()) - await client.get_dataset_schema(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_dataset_schema_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DatasetSchema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_dataset_schema( - 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_dataset_schema_flattened_error(): - client = DocumentServiceClient( - 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_dataset_schema( - document_service.GetDatasetSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_dataset_schema_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DatasetSchema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DatasetSchema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_dataset_schema( - 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_dataset_schema_flattened_error_async(): - client = DocumentServiceAsyncClient( - 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_dataset_schema( - document_service.GetDatasetSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDatasetSchemaRequest, - dict, -]) -def test_update_dataset_schema(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DatasetSchema( - name='name_value', - ) - response = client.update_dataset_schema(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_service.UpdateDatasetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DatasetSchema) - assert response.name == 'name_value' - - -def test_update_dataset_schema_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 = DocumentServiceClient( - 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.update_dataset_schema), - '__call__') as call: - client.update_dataset_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDatasetSchemaRequest() - -@pytest.mark.asyncio -async def test_update_dataset_schema_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDatasetSchemaRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.DatasetSchema( - name='name_value', - )) - response = await client.update_dataset_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDatasetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DatasetSchema) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_dataset_schema_async_from_dict(): - await test_update_dataset_schema_async(request_type=dict) - - -def test_update_dataset_schema_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDatasetSchemaRequest() - - request.dataset_schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_schema), - '__call__') as call: - call.return_value = dataset.DatasetSchema() - client.update_dataset_schema(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', - 'dataset_schema.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_dataset_schema_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDatasetSchemaRequest() - - request.dataset_schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DatasetSchema()) - await client.update_dataset_schema(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', - 'dataset_schema.name=name_value', - ) in kw['metadata'] - - -def test_update_dataset_schema_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DatasetSchema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_dataset_schema( - dataset_schema=dataset.DatasetSchema(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].dataset_schema - mock_val = dataset.DatasetSchema(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_dataset_schema_flattened_error(): - client = DocumentServiceClient( - 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.update_dataset_schema( - document_service.UpdateDatasetSchemaRequest(), - dataset_schema=dataset.DatasetSchema(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_dataset_schema_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DatasetSchema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DatasetSchema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_dataset_schema( - dataset_schema=dataset.DatasetSchema(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].dataset_schema - mock_val = dataset.DatasetSchema(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_dataset_schema_flattened_error_async(): - client = DocumentServiceAsyncClient( - 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.update_dataset_schema( - document_service.UpdateDatasetSchemaRequest(), - dataset_schema=dataset.DatasetSchema(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDatasetRequest, - dict, -]) -def test_update_dataset_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset'}} - request_init["dataset"] = {'gcs_managed_config': {'gcs_prefix': {'gcs_uri_prefix': 'gcs_uri_prefix_value'}}, 'document_warehouse_config': {'collection': 'collection_value', 'schema': 'schema_value'}, 'unmanaged_dataset_config': {}, 'spanner_indexing_config': {}, 'name': 'projects/sample1/locations/sample2/processors/sample3/dataset', 'state': 1} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = document_service.UpdateDatasetRequest.meta.fields["dataset"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["dataset"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["dataset"][field])): - del request_init["dataset"][field][i][subfield] - else: - del request_init["dataset"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_dataset(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_dataset_rest_required_fields(request_type=document_service.UpdateDatasetRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_dataset._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_dataset._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_dataset(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_dataset_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_dataset._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("dataset", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_dataset_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_dataset") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_dataset") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.UpdateDatasetRequest.pb(document_service.UpdateDatasetRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_service.UpdateDatasetRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_dataset_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDatasetRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_dataset(request) - - -def test_update_dataset_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset': {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset'}} - - # get truthy value for each flattened field - mock_args = dict( - dataset=gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_dataset(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{dataset.name=projects/*/locations/*/processors/*/dataset}" % client.transport._host, args[1]) - - -def test_update_dataset_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_dataset( - document_service.UpdateDatasetRequest(), - dataset=gcd_dataset.Dataset(gcs_managed_config=gcd_dataset.Dataset.GCSManagedConfig(gcs_prefix=document_io.GcsPrefix(gcs_uri_prefix='gcs_uri_prefix_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_dataset_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ImportDocumentsRequest, - dict, -]) -def test_import_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_documents_rest_required_fields(request_type=document_service.ImportDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["dataset"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["dataset"] = 'dataset_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "dataset" in jsonified_request - assert jsonified_request["dataset"] == 'dataset_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("dataset", "batchDocumentsImportConfigs", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_import_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_import_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.ImportDocumentsRequest.pb(document_service.ImportDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_service.ImportDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ImportDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_documents(request) - - -def test_import_documents_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - - # get truthy value for each flattened field - mock_args = dict( - dataset='dataset_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.import_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:importDocuments" % client.transport._host, args[1]) - - -def test_import_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.import_documents( - document_service.ImportDocumentsRequest(), - dataset='dataset_value', - ) - - -def test_import_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_service.GetDocumentResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_service.GetDocumentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document_service.GetDocumentResponse) - - -def test_get_document_rest_required_fields(request_type=document_service.GetDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["dataset"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["dataset"] = 'dataset_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("document_id", "page_range", "read_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "dataset" in jsonified_request - assert jsonified_request["dataset"] == 'dataset_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_service.GetDocumentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_service.GetDocumentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("documentId", "pageRange", "readMask", )) & set(("dataset", "documentId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.GetDocumentRequest.pb(document_service.GetDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_service.GetDocumentResponse.to_json(document_service.GetDocumentResponse()) - - request = document_service.GetDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_service.GetDocumentResponse() - - client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_document(request) - - -def test_get_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_service.GetDocumentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - - # get truthy value for each flattened field - mock_args = dict( - dataset='dataset_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_service.GetDocumentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:getDocument" % client.transport._host, args[1]) - - -def test_get_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_document( - document_service.GetDocumentRequest(), - dataset='dataset_value', - ) - - -def test_get_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_documents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_documents_rest_required_fields(request_type=document_service.ListDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["dataset"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["dataset"] = 'dataset_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "dataset" in jsonified_request - assert jsonified_request["dataset"] == 'dataset_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("dataset", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_list_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_list_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.ListDocumentsRequest.pb(document_service.ListDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_service.ListDocumentsResponse.to_json(document_service.ListDocumentsResponse()) - - request = document_service.ListDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_service.ListDocumentsResponse() - - client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_documents(request) - - -def test_list_documents_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - - # get truthy value for each flattened field - mock_args = dict( - dataset='dataset_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:listDocuments" % client.transport._host, args[1]) - - -def test_list_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_documents( - document_service.ListDocumentsRequest(), - dataset='dataset_value', - ) - - -def test_list_documents_rest_pager(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - document_metadata=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - document_metadata=[ - document_service.DocumentMetadata(), - document_service.DocumentMetadata(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_service.ListDocumentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - - pager = client.list_documents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document_service.DocumentMetadata) - for i in results) - - pages = list(client.list_documents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_service.BatchDeleteDocumentsRequest, - dict, -]) -def test_batch_delete_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_delete_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_delete_documents_rest_required_fields(request_type=document_service.BatchDeleteDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["dataset"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["dataset"] = 'dataset_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "dataset" in jsonified_request - assert jsonified_request["dataset"] == 'dataset_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_delete_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_delete_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_delete_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("dataset", "datasetDocuments", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_batch_delete_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_batch_delete_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.BatchDeleteDocumentsRequest.pb(document_service.BatchDeleteDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document_service.BatchDeleteDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_delete_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_delete_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.BatchDeleteDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_documents(request) - - -def test_batch_delete_documents_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset': 'projects/sample1/locations/sample2/processors/sample3/dataset'} - - # get truthy value for each flattened field - mock_args = dict( - dataset='dataset_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_delete_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{dataset=projects/*/locations/*/processors/*/dataset}:batchDeleteDocuments" % client.transport._host, args[1]) - - -def test_batch_delete_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_documents( - document_service.BatchDeleteDocumentsRequest(), - dataset='dataset_value', - ) - - -def test_batch_delete_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDatasetSchemaRequest, - dict, -]) -def test_get_dataset_schema_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset/datasetSchema'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = dataset.DatasetSchema( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dataset.DatasetSchema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_dataset_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DatasetSchema) - assert response.name == 'name_value' - - -def test_get_dataset_schema_rest_required_fields(request_type=document_service.GetDatasetSchemaRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_dataset_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_dataset_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("visible_fields_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = dataset.DatasetSchema() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = dataset.DatasetSchema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_dataset_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_dataset_schema_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_dataset_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("visibleFieldsOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_dataset_schema_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_dataset_schema") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_dataset_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.GetDatasetSchemaRequest.pb(document_service.GetDatasetSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = dataset.DatasetSchema.to_json(dataset.DatasetSchema()) - - request = document_service.GetDatasetSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = dataset.DatasetSchema() - - client.get_dataset_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_dataset_schema_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDatasetSchemaRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset/datasetSchema'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_dataset_schema(request) - - -def test_get_dataset_schema_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = dataset.DatasetSchema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset/datasetSchema'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dataset.DatasetSchema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_dataset_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{name=projects/*/locations/*/processors/*/dataset/datasetSchema}" % client.transport._host, args[1]) - - -def test_get_dataset_schema_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_dataset_schema( - document_service.GetDatasetSchemaRequest(), - name='name_value', - ) - - -def test_get_dataset_schema_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDatasetSchemaRequest, - dict, -]) -def test_update_dataset_schema_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'dataset_schema': {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset/datasetSchema'}} - request_init["dataset_schema"] = {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset/datasetSchema', 'document_schema': {'display_name': 'display_name_value', 'description': 'description_value', 'entity_types': [{'enum_values': {'values': ['values_value1', 'values_value2']}, 'display_name': 'display_name_value', 'name': 'name_value', 'base_types': ['base_types_value1', 'base_types_value2'], 'properties': [{'name': 'name_value', 'display_name': 'display_name_value', 'value_type': 'value_type_value', 'occurrence_type': 1, 'property_metadata': {'inactive': True, 'field_extraction_metadata': {'summary_options': {'length': 1, 'format_': 1}}}}], 'entity_type_metadata': {'inactive': True}}], 'metadata': {'document_splitter': True, 'document_allow_multiple_labels': True, 'prefixed_naming_on_properties': True, 'skip_naming_validation': True}}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = document_service.UpdateDatasetSchemaRequest.meta.fields["dataset_schema"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["dataset_schema"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["dataset_schema"][field])): - del request_init["dataset_schema"][field][i][subfield] - else: - del request_init["dataset_schema"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = dataset.DatasetSchema( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dataset.DatasetSchema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_dataset_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DatasetSchema) - assert response.name == 'name_value' - - -def test_update_dataset_schema_rest_required_fields(request_type=document_service.UpdateDatasetSchemaRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_dataset_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_dataset_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = dataset.DatasetSchema() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = dataset.DatasetSchema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_dataset_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_dataset_schema_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_dataset_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("datasetSchema", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_dataset_schema_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_dataset_schema") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_dataset_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.UpdateDatasetSchemaRequest.pb(document_service.UpdateDatasetSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = dataset.DatasetSchema.to_json(dataset.DatasetSchema()) - - request = document_service.UpdateDatasetSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = dataset.DatasetSchema() - - client.update_dataset_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_dataset_schema_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDatasetSchemaRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'dataset_schema': {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset/datasetSchema'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_dataset_schema(request) - - -def test_update_dataset_schema_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = dataset.DatasetSchema() - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset_schema': {'name': 'projects/sample1/locations/sample2/processors/sample3/dataset/datasetSchema'}} - - # get truthy value for each flattened field - mock_args = dict( - dataset_schema=dataset.DatasetSchema(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dataset.DatasetSchema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_dataset_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta3/{dataset_schema.name=projects/*/locations/*/processors/*/dataset/datasetSchema}" % client.transport._host, args[1]) - - -def test_update_dataset_schema_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_dataset_schema( - document_service.UpdateDatasetSchemaRequest(), - dataset_schema=dataset.DatasetSchema(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_dataset_schema_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentServiceClient.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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentServiceGrpcTransport, - ) - -def test_document_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.documentai_v1beta3.services.document_service.transports.DocumentServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'update_dataset', - 'import_documents', - 'get_document', - 'list_documents', - 'batch_delete_documents', - 'get_dataset_schema', - 'update_dataset_schema', - '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_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_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport( - 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_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_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport() - adc.assert_called_once() - - -def test_document_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) - DocumentServiceClient() - 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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, grpc_helpers), - (transports.DocumentServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_document_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DocumentServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_service_rest_lro_client(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_no_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_with_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='documentai.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'documentai.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://documentai.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.update_dataset._session - session2 = client2.transport.update_dataset._session - assert session1 != session2 - session1 = client1.transport.import_documents._session - session2 = client2.transport.import_documents._session - assert session1 != session2 - session1 = client1.transport.get_document._session - session2 = client2.transport.get_document._session - assert session1 != session2 - session1 = client1.transport.list_documents._session - session2 = client2.transport.list_documents._session - assert session1 != session2 - session1 = client1.transport.batch_delete_documents._session - session2 = client2.transport.batch_delete_documents._session - assert session1 != session2 - session1 = client1.transport.get_dataset_schema._session - session2 = client2.transport.get_dataset_schema._session - assert session1 != session2 - session1 = client1.transport.update_dataset_schema._session - session2 = client2.transport.update_dataset_schema._session - assert session1 != session2 -def test_document_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcTransport( - 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_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcAsyncIOTransport( - 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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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_service_grpc_lro_client(): - client = DocumentServiceClient( - 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_service_grpc_lro_async_client(): - client = DocumentServiceAsyncClient( - 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_dataset_path(): - project = "squid" - location = "clam" - processor = "whelk" - expected = "projects/{project}/locations/{location}/processors/{processor}/dataset".format(project=project, location=location, processor=processor, ) - actual = DocumentServiceClient.dataset_path(project, location, processor) - assert expected == actual - - -def test_parse_dataset_path(): - expected = { - "project": "octopus", - "location": "oyster", - "processor": "nudibranch", - } - path = DocumentServiceClient.dataset_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_dataset_path(path) - assert expected == actual - -def test_dataset_schema_path(): - project = "cuttlefish" - location = "mussel" - processor = "winkle" - expected = "projects/{project}/locations/{location}/processors/{processor}/dataset/datasetSchema".format(project=project, location=location, processor=processor, ) - actual = DocumentServiceClient.dataset_schema_path(project, location, processor) - assert expected == actual - - -def test_parse_dataset_schema_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "processor": "abalone", - } - path = DocumentServiceClient.dataset_schema_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_dataset_schema_path(path) - assert expected == actual - -def test_schema_path(): - project = "squid" - location = "clam" - schema = "whelk" - expected = "projects/{project}/locations/{location}/schemas/{schema}".format(project=project, location=location, schema=schema, ) - actual = DocumentServiceClient.schema_path(project, location, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "octopus", - "location": "oyster", - "schema": "nudibranch", - } - path = DocumentServiceClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_schema_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = DocumentServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = DocumentServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = DocumentServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = DocumentServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = DocumentServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = DocumentServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.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.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentServiceClient.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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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_asyncio"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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_asyncio"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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_asyncio"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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_asyncio"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport), -]) -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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py index 5b3c796cbf2c..fcdd8fb641f0 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py @@ -1855,10 +1855,10 @@ class ImportProcessorVersionRequest(proto.Message): Attributes: processor_version_source (str): - The source processor version to import from. - The source processor version and destination - processor need to be in the same environment and - region. + The source processor version to import from. The source + processor version and destination processor need to be in + the same environment and region. Note that ProcessorVersions + with ``model_type`` ``MODEL_TYPE_LLM`` are not supported. This field is a member of `oneof`_ ``source``. external_processor_version_source (google.cloud.documentai_v1beta3.types.ImportProcessorVersionRequest.ExternalProcessorVersionSource):