From de74104e5037afc2fafa5c3c3bb46c1fedabc834 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 7 Oct 2021 19:30:44 +0000 Subject: [PATCH 1/2] feat: add context manager support in client chore: fix docstring for first attribute of protos committer: @busunkim96 PiperOrigin-RevId: 401271153 Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10 Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9 --- owl-bot-staging/v1beta1/.coveragerc | 17 + owl-bot-staging/v1beta1/MANIFEST.in | 2 + owl-bot-staging/v1beta1/README.rst | 49 + owl-bot-staging/v1beta1/docs/conf.py | 376 + .../data_labeling_service.rst | 10 + .../docs/datalabeling_v1beta1/services.rst | 6 + .../docs/datalabeling_v1beta1/types.rst | 7 + owl-bot-staging/v1beta1/docs/index.rst | 7 + .../google/cloud/datalabeling/__init__.py | 293 + .../google/cloud/datalabeling/py.typed | 2 + .../cloud/datalabeling_v1beta1/__init__.py | 294 + .../datalabeling_v1beta1/gapic_metadata.json | 363 + .../cloud/datalabeling_v1beta1/py.typed | 2 + .../datalabeling_v1beta1/services/__init__.py | 15 + .../data_labeling_service/__init__.py | 22 + .../data_labeling_service/async_client.py | 3337 +++++ .../services/data_labeling_service/client.py | 3451 +++++ .../services/data_labeling_service/pagers.py | 1121 ++ .../transports/__init__.py | 33 + .../data_labeling_service/transports/base.py | 802 ++ .../data_labeling_service/transports/grpc.py | 1177 ++ .../transports/grpc_asyncio.py | 1182 ++ .../datalabeling_v1beta1/types/__init__.py | 308 + .../datalabeling_v1beta1/types/annotation.py | 688 + .../types/annotation_spec_set.py | 108 + .../types/data_labeling_service.py | 1375 ++ .../types/data_payloads.py | 142 + .../datalabeling_v1beta1/types/dataset.py | 645 + .../datalabeling_v1beta1/types/evaluation.py | 405 + .../types/evaluation_job.py | 375 + .../types/human_annotation_config.py | 398 + .../datalabeling_v1beta1/types/instruction.py | 146 + .../datalabeling_v1beta1/types/operations.py | 549 + owl-bot-staging/v1beta1/mypy.ini | 3 + owl-bot-staging/v1beta1/noxfile.py | 132 + .../fixup_datalabeling_v1beta1_keywords.py | 209 + owl-bot-staging/v1beta1/setup.py | 54 + owl-bot-staging/v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../gapic/datalabeling_v1beta1/__init__.py | 16 + .../test_data_labeling_service.py | 10939 ++++++++++++++++ 42 files changed, 29108 insertions(+) create mode 100644 owl-bot-staging/v1beta1/.coveragerc create mode 100644 owl-bot-staging/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1beta1/README.rst create mode 100644 owl-bot-staging/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst create mode 100644 owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst create mode 100644 owl-bot-staging/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py create mode 100644 owl-bot-staging/v1beta1/mypy.ini create mode 100644 owl-bot-staging/v1beta1/noxfile.py create mode 100644 owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py create mode 100644 owl-bot-staging/v1beta1/setup.py create mode 100644 owl-bot-staging/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc new file mode 100644 index 0000000..ecbc77f --- /dev/null +++ b/owl-bot-staging/v1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/datalabeling/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in new file mode 100644 index 0000000..2b92910 --- /dev/null +++ b/owl-bot-staging/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/datalabeling *.py +recursive-include google/cloud/datalabeling_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/owl-bot-staging/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Datalabeling 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 Datalabeling 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py new file mode 100644 index 0000000..ccd09d6 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datalabeling 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-datalabeling" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-datalabeling-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 = [ + ( + master_doc, + "google-cloud-datalabeling.tex", + u"google-cloud-datalabeling 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 = [ + ( + master_doc, + "google-cloud-datalabeling", + u"Google Cloud Datalabeling 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 = [ + ( + master_doc, + "google-cloud-datalabeling", + u"google-cloud-datalabeling Documentation", + author, + "google-cloud-datalabeling", + "GAPIC library for Google Cloud Datalabeling 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/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst new file mode 100644 index 0000000..d2524a1 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst @@ -0,0 +1,10 @@ +DataLabelingService +------------------------------------- + +.. automodule:: google.cloud.datalabeling_v1beta1.services.data_labeling_service + :members: + :inherited-members: + +.. automodule:: google.cloud.datalabeling_v1beta1.services.data_labeling_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst new file mode 100644 index 0000000..2ddfb76 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Datalabeling v1beta1 API +================================================== +.. toctree:: + :maxdepth: 2 + + data_labeling_service diff --git a/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst new file mode 100644 index 0000000..452ea6c --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Datalabeling v1beta1 API +=============================================== + +.. automodule:: google.cloud.datalabeling_v1beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst new file mode 100644 index 0000000..b73f31f --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + datalabeling_v1beta1/services + datalabeling_v1beta1/types diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py new file mode 100644 index 0000000..41cb770 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py @@ -0,0 +1,293 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.datalabeling_v1beta1.services.data_labeling_service.client import DataLabelingServiceClient +from google.cloud.datalabeling_v1beta1.services.data_labeling_service.async_client import DataLabelingServiceAsyncClient + +from google.cloud.datalabeling_v1beta1.types.annotation import Annotation +from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationMetadata +from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationValue +from google.cloud.datalabeling_v1beta1.types.annotation import BoundingPoly +from google.cloud.datalabeling_v1beta1.types.annotation import ImageBoundingPolyAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import ImageClassificationAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import ImagePolylineAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import ImageSegmentationAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import NormalizedBoundingPoly +from google.cloud.datalabeling_v1beta1.types.annotation import NormalizedPolyline +from google.cloud.datalabeling_v1beta1.types.annotation import NormalizedVertex +from google.cloud.datalabeling_v1beta1.types.annotation import ObjectTrackingFrame +from google.cloud.datalabeling_v1beta1.types.annotation import OperatorMetadata +from google.cloud.datalabeling_v1beta1.types.annotation import Polyline +from google.cloud.datalabeling_v1beta1.types.annotation import SequentialSegment +from google.cloud.datalabeling_v1beta1.types.annotation import TextClassificationAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import TextEntityExtractionAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import TimeSegment +from google.cloud.datalabeling_v1beta1.types.annotation import Vertex +from google.cloud.datalabeling_v1beta1.types.annotation import VideoClassificationAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import VideoEventAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import VideoObjectTrackingAnnotation +from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationSentiment +from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationSource +from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationType +from google.cloud.datalabeling_v1beta1.types.annotation_spec_set import AnnotationSpec +from google.cloud.datalabeling_v1beta1.types.annotation_spec_set import AnnotationSpecSet +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateAnnotationSpecSetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateDatasetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateEvaluationJobRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateInstructionRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteAnnotatedDatasetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteAnnotationSpecSetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteDatasetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteEvaluationJobRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteInstructionRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ExportDataRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetAnnotatedDatasetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetAnnotationSpecSetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetDataItemRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetDatasetRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetEvaluationJobRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetEvaluationRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetExampleRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetInstructionRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ImportDataRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import LabelImageRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import LabelTextRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import LabelVideoRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotatedDatasetsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotatedDatasetsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotationSpecSetsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotationSpecSetsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDataItemsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDataItemsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDatasetsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDatasetsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListEvaluationJobsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListEvaluationJobsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListExamplesRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListExamplesResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListInstructionsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListInstructionsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import PauseEvaluationJobRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ResumeEvaluationJobRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchEvaluationsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchEvaluationsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchExampleComparisonsRequest +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchExampleComparisonsResponse +from google.cloud.datalabeling_v1beta1.types.data_labeling_service import UpdateEvaluationJobRequest +from google.cloud.datalabeling_v1beta1.types.data_payloads import ImagePayload +from google.cloud.datalabeling_v1beta1.types.data_payloads import TextPayload +from google.cloud.datalabeling_v1beta1.types.data_payloads import VideoPayload +from google.cloud.datalabeling_v1beta1.types.data_payloads import VideoThumbnail +from google.cloud.datalabeling_v1beta1.types.dataset import AnnotatedDataset +from google.cloud.datalabeling_v1beta1.types.dataset import AnnotatedDatasetMetadata +from google.cloud.datalabeling_v1beta1.types.dataset import BigQuerySource +from google.cloud.datalabeling_v1beta1.types.dataset import ClassificationMetadata +from google.cloud.datalabeling_v1beta1.types.dataset import DataItem +from google.cloud.datalabeling_v1beta1.types.dataset import Dataset +from google.cloud.datalabeling_v1beta1.types.dataset import Example +from google.cloud.datalabeling_v1beta1.types.dataset import GcsDestination +from google.cloud.datalabeling_v1beta1.types.dataset import GcsFolderDestination +from google.cloud.datalabeling_v1beta1.types.dataset import GcsSource +from google.cloud.datalabeling_v1beta1.types.dataset import InputConfig +from google.cloud.datalabeling_v1beta1.types.dataset import LabelStats +from google.cloud.datalabeling_v1beta1.types.dataset import OutputConfig +from google.cloud.datalabeling_v1beta1.types.dataset import TextMetadata +from google.cloud.datalabeling_v1beta1.types.dataset import DataType +from google.cloud.datalabeling_v1beta1.types.evaluation import BoundingBoxEvaluationOptions +from google.cloud.datalabeling_v1beta1.types.evaluation import ClassificationMetrics +from google.cloud.datalabeling_v1beta1.types.evaluation import ConfusionMatrix +from google.cloud.datalabeling_v1beta1.types.evaluation import Evaluation +from google.cloud.datalabeling_v1beta1.types.evaluation import EvaluationConfig +from google.cloud.datalabeling_v1beta1.types.evaluation import EvaluationMetrics +from google.cloud.datalabeling_v1beta1.types.evaluation import ObjectDetectionMetrics +from google.cloud.datalabeling_v1beta1.types.evaluation import PrCurve +from google.cloud.datalabeling_v1beta1.types.evaluation_job import Attempt +from google.cloud.datalabeling_v1beta1.types.evaluation_job import EvaluationJob +from google.cloud.datalabeling_v1beta1.types.evaluation_job import EvaluationJobAlertConfig +from google.cloud.datalabeling_v1beta1.types.evaluation_job import EvaluationJobConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import BoundingPolyConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import EventConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import HumanAnnotationConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import ImageClassificationConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import ObjectDetectionConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import ObjectTrackingConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import PolylineConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import SegmentationConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import SentimentConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import TextClassificationConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import TextEntityExtractionConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import VideoClassificationConfig +from google.cloud.datalabeling_v1beta1.types.human_annotation_config import StringAggregationType +from google.cloud.datalabeling_v1beta1.types.instruction import CsvInstruction +from google.cloud.datalabeling_v1beta1.types.instruction import Instruction +from google.cloud.datalabeling_v1beta1.types.instruction import PdfInstruction +from google.cloud.datalabeling_v1beta1.types.operations import CreateInstructionMetadata +from google.cloud.datalabeling_v1beta1.types.operations import ExportDataOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import ExportDataOperationResponse +from google.cloud.datalabeling_v1beta1.types.operations import ImportDataOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import ImportDataOperationResponse +from google.cloud.datalabeling_v1beta1.types.operations import LabelImageBoundingBoxOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelImageBoundingPolyOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelImageClassificationOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelImageOrientedBoundingBoxOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelImagePolylineOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelImageSegmentationOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelTextClassificationOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelTextEntityExtractionOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoClassificationOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoEventOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoObjectDetectionOperationMetadata +from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoObjectTrackingOperationMetadata + +__all__ = ('DataLabelingServiceClient', + 'DataLabelingServiceAsyncClient', + 'Annotation', + 'AnnotationMetadata', + 'AnnotationValue', + 'BoundingPoly', + 'ImageBoundingPolyAnnotation', + 'ImageClassificationAnnotation', + 'ImagePolylineAnnotation', + 'ImageSegmentationAnnotation', + 'NormalizedBoundingPoly', + 'NormalizedPolyline', + 'NormalizedVertex', + 'ObjectTrackingFrame', + 'OperatorMetadata', + 'Polyline', + 'SequentialSegment', + 'TextClassificationAnnotation', + 'TextEntityExtractionAnnotation', + 'TimeSegment', + 'Vertex', + 'VideoClassificationAnnotation', + 'VideoEventAnnotation', + 'VideoObjectTrackingAnnotation', + 'AnnotationSentiment', + 'AnnotationSource', + 'AnnotationType', + 'AnnotationSpec', + 'AnnotationSpecSet', + 'CreateAnnotationSpecSetRequest', + 'CreateDatasetRequest', + 'CreateEvaluationJobRequest', + 'CreateInstructionRequest', + 'DeleteAnnotatedDatasetRequest', + 'DeleteAnnotationSpecSetRequest', + 'DeleteDatasetRequest', + 'DeleteEvaluationJobRequest', + 'DeleteInstructionRequest', + 'ExportDataRequest', + 'GetAnnotatedDatasetRequest', + 'GetAnnotationSpecSetRequest', + 'GetDataItemRequest', + 'GetDatasetRequest', + 'GetEvaluationJobRequest', + 'GetEvaluationRequest', + 'GetExampleRequest', + 'GetInstructionRequest', + 'ImportDataRequest', + 'LabelImageRequest', + 'LabelTextRequest', + 'LabelVideoRequest', + 'ListAnnotatedDatasetsRequest', + 'ListAnnotatedDatasetsResponse', + 'ListAnnotationSpecSetsRequest', + 'ListAnnotationSpecSetsResponse', + 'ListDataItemsRequest', + 'ListDataItemsResponse', + 'ListDatasetsRequest', + 'ListDatasetsResponse', + 'ListEvaluationJobsRequest', + 'ListEvaluationJobsResponse', + 'ListExamplesRequest', + 'ListExamplesResponse', + 'ListInstructionsRequest', + 'ListInstructionsResponse', + 'PauseEvaluationJobRequest', + 'ResumeEvaluationJobRequest', + 'SearchEvaluationsRequest', + 'SearchEvaluationsResponse', + 'SearchExampleComparisonsRequest', + 'SearchExampleComparisonsResponse', + 'UpdateEvaluationJobRequest', + 'ImagePayload', + 'TextPayload', + 'VideoPayload', + 'VideoThumbnail', + 'AnnotatedDataset', + 'AnnotatedDatasetMetadata', + 'BigQuerySource', + 'ClassificationMetadata', + 'DataItem', + 'Dataset', + 'Example', + 'GcsDestination', + 'GcsFolderDestination', + 'GcsSource', + 'InputConfig', + 'LabelStats', + 'OutputConfig', + 'TextMetadata', + 'DataType', + 'BoundingBoxEvaluationOptions', + 'ClassificationMetrics', + 'ConfusionMatrix', + 'Evaluation', + 'EvaluationConfig', + 'EvaluationMetrics', + 'ObjectDetectionMetrics', + 'PrCurve', + 'Attempt', + 'EvaluationJob', + 'EvaluationJobAlertConfig', + 'EvaluationJobConfig', + 'BoundingPolyConfig', + 'EventConfig', + 'HumanAnnotationConfig', + 'ImageClassificationConfig', + 'ObjectDetectionConfig', + 'ObjectTrackingConfig', + 'PolylineConfig', + 'SegmentationConfig', + 'SentimentConfig', + 'TextClassificationConfig', + 'TextEntityExtractionConfig', + 'VideoClassificationConfig', + 'StringAggregationType', + 'CsvInstruction', + 'Instruction', + 'PdfInstruction', + 'CreateInstructionMetadata', + 'ExportDataOperationMetadata', + 'ExportDataOperationResponse', + 'ImportDataOperationMetadata', + 'ImportDataOperationResponse', + 'LabelImageBoundingBoxOperationMetadata', + 'LabelImageBoundingPolyOperationMetadata', + 'LabelImageClassificationOperationMetadata', + 'LabelImageOrientedBoundingBoxOperationMetadata', + 'LabelImagePolylineOperationMetadata', + 'LabelImageSegmentationOperationMetadata', + 'LabelOperationMetadata', + 'LabelTextClassificationOperationMetadata', + 'LabelTextEntityExtractionOperationMetadata', + 'LabelVideoClassificationOperationMetadata', + 'LabelVideoEventOperationMetadata', + 'LabelVideoObjectDetectionOperationMetadata', + 'LabelVideoObjectTrackingOperationMetadata', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed b/owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed new file mode 100644 index 0000000..1d27d78 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-datalabeling package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py new file mode 100644 index 0000000..ff186c4 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py @@ -0,0 +1,294 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .services.data_labeling_service import DataLabelingServiceClient +from .services.data_labeling_service import DataLabelingServiceAsyncClient + +from .types.annotation import Annotation +from .types.annotation import AnnotationMetadata +from .types.annotation import AnnotationValue +from .types.annotation import BoundingPoly +from .types.annotation import ImageBoundingPolyAnnotation +from .types.annotation import ImageClassificationAnnotation +from .types.annotation import ImagePolylineAnnotation +from .types.annotation import ImageSegmentationAnnotation +from .types.annotation import NormalizedBoundingPoly +from .types.annotation import NormalizedPolyline +from .types.annotation import NormalizedVertex +from .types.annotation import ObjectTrackingFrame +from .types.annotation import OperatorMetadata +from .types.annotation import Polyline +from .types.annotation import SequentialSegment +from .types.annotation import TextClassificationAnnotation +from .types.annotation import TextEntityExtractionAnnotation +from .types.annotation import TimeSegment +from .types.annotation import Vertex +from .types.annotation import VideoClassificationAnnotation +from .types.annotation import VideoEventAnnotation +from .types.annotation import VideoObjectTrackingAnnotation +from .types.annotation import AnnotationSentiment +from .types.annotation import AnnotationSource +from .types.annotation import AnnotationType +from .types.annotation_spec_set import AnnotationSpec +from .types.annotation_spec_set import AnnotationSpecSet +from .types.data_labeling_service import CreateAnnotationSpecSetRequest +from .types.data_labeling_service import CreateDatasetRequest +from .types.data_labeling_service import CreateEvaluationJobRequest +from .types.data_labeling_service import CreateInstructionRequest +from .types.data_labeling_service import DeleteAnnotatedDatasetRequest +from .types.data_labeling_service import DeleteAnnotationSpecSetRequest +from .types.data_labeling_service import DeleteDatasetRequest +from .types.data_labeling_service import DeleteEvaluationJobRequest +from .types.data_labeling_service import DeleteInstructionRequest +from .types.data_labeling_service import ExportDataRequest +from .types.data_labeling_service import GetAnnotatedDatasetRequest +from .types.data_labeling_service import GetAnnotationSpecSetRequest +from .types.data_labeling_service import GetDataItemRequest +from .types.data_labeling_service import GetDatasetRequest +from .types.data_labeling_service import GetEvaluationJobRequest +from .types.data_labeling_service import GetEvaluationRequest +from .types.data_labeling_service import GetExampleRequest +from .types.data_labeling_service import GetInstructionRequest +from .types.data_labeling_service import ImportDataRequest +from .types.data_labeling_service import LabelImageRequest +from .types.data_labeling_service import LabelTextRequest +from .types.data_labeling_service import LabelVideoRequest +from .types.data_labeling_service import ListAnnotatedDatasetsRequest +from .types.data_labeling_service import ListAnnotatedDatasetsResponse +from .types.data_labeling_service import ListAnnotationSpecSetsRequest +from .types.data_labeling_service import ListAnnotationSpecSetsResponse +from .types.data_labeling_service import ListDataItemsRequest +from .types.data_labeling_service import ListDataItemsResponse +from .types.data_labeling_service import ListDatasetsRequest +from .types.data_labeling_service import ListDatasetsResponse +from .types.data_labeling_service import ListEvaluationJobsRequest +from .types.data_labeling_service import ListEvaluationJobsResponse +from .types.data_labeling_service import ListExamplesRequest +from .types.data_labeling_service import ListExamplesResponse +from .types.data_labeling_service import ListInstructionsRequest +from .types.data_labeling_service import ListInstructionsResponse +from .types.data_labeling_service import PauseEvaluationJobRequest +from .types.data_labeling_service import ResumeEvaluationJobRequest +from .types.data_labeling_service import SearchEvaluationsRequest +from .types.data_labeling_service import SearchEvaluationsResponse +from .types.data_labeling_service import SearchExampleComparisonsRequest +from .types.data_labeling_service import SearchExampleComparisonsResponse +from .types.data_labeling_service import UpdateEvaluationJobRequest +from .types.data_payloads import ImagePayload +from .types.data_payloads import TextPayload +from .types.data_payloads import VideoPayload +from .types.data_payloads import VideoThumbnail +from .types.dataset import AnnotatedDataset +from .types.dataset import AnnotatedDatasetMetadata +from .types.dataset import BigQuerySource +from .types.dataset import ClassificationMetadata +from .types.dataset import DataItem +from .types.dataset import Dataset +from .types.dataset import Example +from .types.dataset import GcsDestination +from .types.dataset import GcsFolderDestination +from .types.dataset import GcsSource +from .types.dataset import InputConfig +from .types.dataset import LabelStats +from .types.dataset import OutputConfig +from .types.dataset import TextMetadata +from .types.dataset import DataType +from .types.evaluation import BoundingBoxEvaluationOptions +from .types.evaluation import ClassificationMetrics +from .types.evaluation import ConfusionMatrix +from .types.evaluation import Evaluation +from .types.evaluation import EvaluationConfig +from .types.evaluation import EvaluationMetrics +from .types.evaluation import ObjectDetectionMetrics +from .types.evaluation import PrCurve +from .types.evaluation_job import Attempt +from .types.evaluation_job import EvaluationJob +from .types.evaluation_job import EvaluationJobAlertConfig +from .types.evaluation_job import EvaluationJobConfig +from .types.human_annotation_config import BoundingPolyConfig +from .types.human_annotation_config import EventConfig +from .types.human_annotation_config import HumanAnnotationConfig +from .types.human_annotation_config import ImageClassificationConfig +from .types.human_annotation_config import ObjectDetectionConfig +from .types.human_annotation_config import ObjectTrackingConfig +from .types.human_annotation_config import PolylineConfig +from .types.human_annotation_config import SegmentationConfig +from .types.human_annotation_config import SentimentConfig +from .types.human_annotation_config import TextClassificationConfig +from .types.human_annotation_config import TextEntityExtractionConfig +from .types.human_annotation_config import VideoClassificationConfig +from .types.human_annotation_config import StringAggregationType +from .types.instruction import CsvInstruction +from .types.instruction import Instruction +from .types.instruction import PdfInstruction +from .types.operations import CreateInstructionMetadata +from .types.operations import ExportDataOperationMetadata +from .types.operations import ExportDataOperationResponse +from .types.operations import ImportDataOperationMetadata +from .types.operations import ImportDataOperationResponse +from .types.operations import LabelImageBoundingBoxOperationMetadata +from .types.operations import LabelImageBoundingPolyOperationMetadata +from .types.operations import LabelImageClassificationOperationMetadata +from .types.operations import LabelImageOrientedBoundingBoxOperationMetadata +from .types.operations import LabelImagePolylineOperationMetadata +from .types.operations import LabelImageSegmentationOperationMetadata +from .types.operations import LabelOperationMetadata +from .types.operations import LabelTextClassificationOperationMetadata +from .types.operations import LabelTextEntityExtractionOperationMetadata +from .types.operations import LabelVideoClassificationOperationMetadata +from .types.operations import LabelVideoEventOperationMetadata +from .types.operations import LabelVideoObjectDetectionOperationMetadata +from .types.operations import LabelVideoObjectTrackingOperationMetadata + +__all__ = ( + 'DataLabelingServiceAsyncClient', +'AnnotatedDataset', +'AnnotatedDatasetMetadata', +'Annotation', +'AnnotationMetadata', +'AnnotationSentiment', +'AnnotationSource', +'AnnotationSpec', +'AnnotationSpecSet', +'AnnotationType', +'AnnotationValue', +'Attempt', +'BigQuerySource', +'BoundingBoxEvaluationOptions', +'BoundingPoly', +'BoundingPolyConfig', +'ClassificationMetadata', +'ClassificationMetrics', +'ConfusionMatrix', +'CreateAnnotationSpecSetRequest', +'CreateDatasetRequest', +'CreateEvaluationJobRequest', +'CreateInstructionMetadata', +'CreateInstructionRequest', +'CsvInstruction', +'DataItem', +'DataLabelingServiceClient', +'DataType', +'Dataset', +'DeleteAnnotatedDatasetRequest', +'DeleteAnnotationSpecSetRequest', +'DeleteDatasetRequest', +'DeleteEvaluationJobRequest', +'DeleteInstructionRequest', +'Evaluation', +'EvaluationConfig', +'EvaluationJob', +'EvaluationJobAlertConfig', +'EvaluationJobConfig', +'EvaluationMetrics', +'EventConfig', +'Example', +'ExportDataOperationMetadata', +'ExportDataOperationResponse', +'ExportDataRequest', +'GcsDestination', +'GcsFolderDestination', +'GcsSource', +'GetAnnotatedDatasetRequest', +'GetAnnotationSpecSetRequest', +'GetDataItemRequest', +'GetDatasetRequest', +'GetEvaluationJobRequest', +'GetEvaluationRequest', +'GetExampleRequest', +'GetInstructionRequest', +'HumanAnnotationConfig', +'ImageBoundingPolyAnnotation', +'ImageClassificationAnnotation', +'ImageClassificationConfig', +'ImagePayload', +'ImagePolylineAnnotation', +'ImageSegmentationAnnotation', +'ImportDataOperationMetadata', +'ImportDataOperationResponse', +'ImportDataRequest', +'InputConfig', +'Instruction', +'LabelImageBoundingBoxOperationMetadata', +'LabelImageBoundingPolyOperationMetadata', +'LabelImageClassificationOperationMetadata', +'LabelImageOrientedBoundingBoxOperationMetadata', +'LabelImagePolylineOperationMetadata', +'LabelImageRequest', +'LabelImageSegmentationOperationMetadata', +'LabelOperationMetadata', +'LabelStats', +'LabelTextClassificationOperationMetadata', +'LabelTextEntityExtractionOperationMetadata', +'LabelTextRequest', +'LabelVideoClassificationOperationMetadata', +'LabelVideoEventOperationMetadata', +'LabelVideoObjectDetectionOperationMetadata', +'LabelVideoObjectTrackingOperationMetadata', +'LabelVideoRequest', +'ListAnnotatedDatasetsRequest', +'ListAnnotatedDatasetsResponse', +'ListAnnotationSpecSetsRequest', +'ListAnnotationSpecSetsResponse', +'ListDataItemsRequest', +'ListDataItemsResponse', +'ListDatasetsRequest', +'ListDatasetsResponse', +'ListEvaluationJobsRequest', +'ListEvaluationJobsResponse', +'ListExamplesRequest', +'ListExamplesResponse', +'ListInstructionsRequest', +'ListInstructionsResponse', +'NormalizedBoundingPoly', +'NormalizedPolyline', +'NormalizedVertex', +'ObjectDetectionConfig', +'ObjectDetectionMetrics', +'ObjectTrackingConfig', +'ObjectTrackingFrame', +'OperatorMetadata', +'OutputConfig', +'PauseEvaluationJobRequest', +'PdfInstruction', +'Polyline', +'PolylineConfig', +'PrCurve', +'ResumeEvaluationJobRequest', +'SearchEvaluationsRequest', +'SearchEvaluationsResponse', +'SearchExampleComparisonsRequest', +'SearchExampleComparisonsResponse', +'SegmentationConfig', +'SentimentConfig', +'SequentialSegment', +'StringAggregationType', +'TextClassificationAnnotation', +'TextClassificationConfig', +'TextEntityExtractionAnnotation', +'TextEntityExtractionConfig', +'TextMetadata', +'TextPayload', +'TimeSegment', +'UpdateEvaluationJobRequest', +'Vertex', +'VideoClassificationAnnotation', +'VideoClassificationConfig', +'VideoEventAnnotation', +'VideoObjectTrackingAnnotation', +'VideoPayload', +'VideoThumbnail', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json new file mode 100644 index 0000000..d98e553 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json @@ -0,0 +1,363 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.datalabeling_v1beta1", + "protoPackage": "google.cloud.datalabeling.v1beta1", + "schema": "1.0", + "services": { + "DataLabelingService": { + "clients": { + "grpc": { + "libraryClient": "DataLabelingServiceClient", + "rpcs": { + "CreateAnnotationSpecSet": { + "methods": [ + "create_annotation_spec_set" + ] + }, + "CreateDataset": { + "methods": [ + "create_dataset" + ] + }, + "CreateEvaluationJob": { + "methods": [ + "create_evaluation_job" + ] + }, + "CreateInstruction": { + "methods": [ + "create_instruction" + ] + }, + "DeleteAnnotatedDataset": { + "methods": [ + "delete_annotated_dataset" + ] + }, + "DeleteAnnotationSpecSet": { + "methods": [ + "delete_annotation_spec_set" + ] + }, + "DeleteDataset": { + "methods": [ + "delete_dataset" + ] + }, + "DeleteEvaluationJob": { + "methods": [ + "delete_evaluation_job" + ] + }, + "DeleteInstruction": { + "methods": [ + "delete_instruction" + ] + }, + "ExportData": { + "methods": [ + "export_data" + ] + }, + "GetAnnotatedDataset": { + "methods": [ + "get_annotated_dataset" + ] + }, + "GetAnnotationSpecSet": { + "methods": [ + "get_annotation_spec_set" + ] + }, + "GetDataItem": { + "methods": [ + "get_data_item" + ] + }, + "GetDataset": { + "methods": [ + "get_dataset" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetEvaluationJob": { + "methods": [ + "get_evaluation_job" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "GetInstruction": { + "methods": [ + "get_instruction" + ] + }, + "ImportData": { + "methods": [ + "import_data" + ] + }, + "LabelImage": { + "methods": [ + "label_image" + ] + }, + "LabelText": { + "methods": [ + "label_text" + ] + }, + "LabelVideo": { + "methods": [ + "label_video" + ] + }, + "ListAnnotatedDatasets": { + "methods": [ + "list_annotated_datasets" + ] + }, + "ListAnnotationSpecSets": { + "methods": [ + "list_annotation_spec_sets" + ] + }, + "ListDataItems": { + "methods": [ + "list_data_items" + ] + }, + "ListDatasets": { + "methods": [ + "list_datasets" + ] + }, + "ListEvaluationJobs": { + "methods": [ + "list_evaluation_jobs" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "ListInstructions": { + "methods": [ + "list_instructions" + ] + }, + "PauseEvaluationJob": { + "methods": [ + "pause_evaluation_job" + ] + }, + "ResumeEvaluationJob": { + "methods": [ + "resume_evaluation_job" + ] + }, + "SearchEvaluations": { + "methods": [ + "search_evaluations" + ] + }, + "SearchExampleComparisons": { + "methods": [ + "search_example_comparisons" + ] + }, + "UpdateEvaluationJob": { + "methods": [ + "update_evaluation_job" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataLabelingServiceAsyncClient", + "rpcs": { + "CreateAnnotationSpecSet": { + "methods": [ + "create_annotation_spec_set" + ] + }, + "CreateDataset": { + "methods": [ + "create_dataset" + ] + }, + "CreateEvaluationJob": { + "methods": [ + "create_evaluation_job" + ] + }, + "CreateInstruction": { + "methods": [ + "create_instruction" + ] + }, + "DeleteAnnotatedDataset": { + "methods": [ + "delete_annotated_dataset" + ] + }, + "DeleteAnnotationSpecSet": { + "methods": [ + "delete_annotation_spec_set" + ] + }, + "DeleteDataset": { + "methods": [ + "delete_dataset" + ] + }, + "DeleteEvaluationJob": { + "methods": [ + "delete_evaluation_job" + ] + }, + "DeleteInstruction": { + "methods": [ + "delete_instruction" + ] + }, + "ExportData": { + "methods": [ + "export_data" + ] + }, + "GetAnnotatedDataset": { + "methods": [ + "get_annotated_dataset" + ] + }, + "GetAnnotationSpecSet": { + "methods": [ + "get_annotation_spec_set" + ] + }, + "GetDataItem": { + "methods": [ + "get_data_item" + ] + }, + "GetDataset": { + "methods": [ + "get_dataset" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetEvaluationJob": { + "methods": [ + "get_evaluation_job" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "GetInstruction": { + "methods": [ + "get_instruction" + ] + }, + "ImportData": { + "methods": [ + "import_data" + ] + }, + "LabelImage": { + "methods": [ + "label_image" + ] + }, + "LabelText": { + "methods": [ + "label_text" + ] + }, + "LabelVideo": { + "methods": [ + "label_video" + ] + }, + "ListAnnotatedDatasets": { + "methods": [ + "list_annotated_datasets" + ] + }, + "ListAnnotationSpecSets": { + "methods": [ + "list_annotation_spec_sets" + ] + }, + "ListDataItems": { + "methods": [ + "list_data_items" + ] + }, + "ListDatasets": { + "methods": [ + "list_datasets" + ] + }, + "ListEvaluationJobs": { + "methods": [ + "list_evaluation_jobs" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "ListInstructions": { + "methods": [ + "list_instructions" + ] + }, + "PauseEvaluationJob": { + "methods": [ + "pause_evaluation_job" + ] + }, + "ResumeEvaluationJob": { + "methods": [ + "resume_evaluation_job" + ] + }, + "SearchEvaluations": { + "methods": [ + "search_evaluations" + ] + }, + "SearchExampleComparisons": { + "methods": [ + "search_example_comparisons" + ] + }, + "UpdateEvaluationJob": { + "methods": [ + "update_evaluation_job" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed new file mode 100644 index 0000000..1d27d78 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-datalabeling package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py new file mode 100644 index 0000000..7926b83 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 DataLabelingServiceClient +from .async_client import DataLabelingServiceAsyncClient + +__all__ = ( + 'DataLabelingServiceClient', + 'DataLabelingServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py new file mode 100644 index 0000000..68e4f79 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py @@ -0,0 +1,3337 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.datalabeling_v1beta1.services.data_labeling_service import pagers +from google.cloud.datalabeling_v1beta1.types import annotation +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import data_labeling_service +from google.cloud.datalabeling_v1beta1.types import data_payloads +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job +from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job +from google.cloud.datalabeling_v1beta1.types import human_annotation_config +from google.cloud.datalabeling_v1beta1.types import instruction +from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction +from google.cloud.datalabeling_v1beta1.types import operations +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataLabelingServiceGrpcAsyncIOTransport +from .client import DataLabelingServiceClient + + +class DataLabelingServiceAsyncClient: + """Service for the AI Platform Data Labeling API.""" + + _client: DataLabelingServiceClient + + DEFAULT_ENDPOINT = DataLabelingServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataLabelingServiceClient.DEFAULT_MTLS_ENDPOINT + + annotated_dataset_path = staticmethod(DataLabelingServiceClient.annotated_dataset_path) + parse_annotated_dataset_path = staticmethod(DataLabelingServiceClient.parse_annotated_dataset_path) + annotation_spec_set_path = staticmethod(DataLabelingServiceClient.annotation_spec_set_path) + parse_annotation_spec_set_path = staticmethod(DataLabelingServiceClient.parse_annotation_spec_set_path) + data_item_path = staticmethod(DataLabelingServiceClient.data_item_path) + parse_data_item_path = staticmethod(DataLabelingServiceClient.parse_data_item_path) + dataset_path = staticmethod(DataLabelingServiceClient.dataset_path) + parse_dataset_path = staticmethod(DataLabelingServiceClient.parse_dataset_path) + evaluation_path = staticmethod(DataLabelingServiceClient.evaluation_path) + parse_evaluation_path = staticmethod(DataLabelingServiceClient.parse_evaluation_path) + evaluation_job_path = staticmethod(DataLabelingServiceClient.evaluation_job_path) + parse_evaluation_job_path = staticmethod(DataLabelingServiceClient.parse_evaluation_job_path) + example_path = staticmethod(DataLabelingServiceClient.example_path) + parse_example_path = staticmethod(DataLabelingServiceClient.parse_example_path) + instruction_path = staticmethod(DataLabelingServiceClient.instruction_path) + parse_instruction_path = staticmethod(DataLabelingServiceClient.parse_instruction_path) + common_billing_account_path = staticmethod(DataLabelingServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataLabelingServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataLabelingServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DataLabelingServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DataLabelingServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DataLabelingServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DataLabelingServiceClient.common_project_path) + parse_common_project_path = staticmethod(DataLabelingServiceClient.parse_common_project_path) + common_location_path = staticmethod(DataLabelingServiceClient.common_location_path) + parse_common_location_path = staticmethod(DataLabelingServiceClient.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: + DataLabelingServiceAsyncClient: The constructed client. + """ + return DataLabelingServiceClient.from_service_account_info.__func__(DataLabelingServiceAsyncClient, 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: + DataLabelingServiceAsyncClient: The constructed client. + """ + return DataLabelingServiceClient.from_service_account_file.__func__(DataLabelingServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DataLabelingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataLabelingServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataLabelingServiceClient).get_transport_class, type(DataLabelingServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DataLabelingServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data labeling 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, ~.DataLabelingServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DataLabelingServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_dataset(self, + request: data_labeling_service.CreateDatasetRequest = None, + *, + parent: str = None, + dataset: gcd_dataset.Dataset = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_dataset.Dataset: + r"""Creates dataset. If success return a Dataset + resource. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.CreateDatasetRequest`): + The request object. Request message for CreateDataset. + parent (:class:`str`): + Required. Dataset resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dataset (:class:`google.cloud.datalabeling_v1beta1.types.Dataset`): + Required. The dataset to be created. + 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.datalabeling_v1beta1.types.Dataset: + Dataset is the resource to hold your + data. You can request multiple labeling + tasks for a dataset while each one will + generate an AnnotatedDataset. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, 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 = data_labeling_service.CreateDatasetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + 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.create_dataset, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_dataset(self, + request: data_labeling_service.GetDatasetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.Dataset: + r"""Gets dataset by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetDatasetRequest`): + The request object. Request message for GetDataSet. + name (:class:`str`): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + 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.datalabeling_v1beta1.types.Dataset: + Dataset is the resource to hold your + data. You can request multiple labeling + tasks for a dataset while each one will + generate an AnnotatedDataset. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.GetDatasetRequest(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, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_datasets(self, + request: data_labeling_service.ListDatasetsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDatasetsAsyncPager: + r"""Lists datasets under a project. Pagination is + supported. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsRequest`): + The request object. Request message for ListDataset. + parent (:class:`str`): + Required. Dataset resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter on dataset is not + supported at this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDatasetsAsyncPager: + Results of listing datasets within a + project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.ListDatasetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_datasets, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDatasetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_dataset(self, + request: data_labeling_service.DeleteDatasetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a dataset by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteDatasetRequest`): + The request object. Request message for DeleteDataset. + name (:class:`str`): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.DeleteDatasetRequest(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_dataset, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_data(self, + request: data_labeling_service.ImportDataRequest = None, + *, + name: str = None, + input_config: dataset.InputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports data into dataset based on source locations + defined in request. It can be called multiple times for + the same dataset. Each dataset can only have one long + running operation running on it. For example, no + labeling task (also long running operation) can be + started while importing is still ongoing. Vice versa. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ImportDataRequest`): + The request object. Request message for ImportData API. + name (:class:`str`): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`google.cloud.datalabeling_v1beta1.types.InputConfig`): + Required. Specify the input source of + the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.datalabeling_v1beta1.types.ImportDataOperationResponse` + Response used for ImportData longrunning operation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, input_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 = data_labeling_service.ImportDataRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if input_config is not None: + request.input_config = input_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.import_data, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + operations.ImportDataOperationResponse, + metadata_type=operations.ImportDataOperationMetadata, + ) + + # Done; return the response. + return response + + async def export_data(self, + request: data_labeling_service.ExportDataRequest = None, + *, + name: str = None, + annotated_dataset: str = None, + filter: str = None, + output_config: dataset.OutputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports data and annotations from dataset. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ExportDataRequest`): + The request object. Request message for ExportData API. + name (:class:`str`): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotated_dataset (:class:`str`): + Required. Annotated dataset resource name. DataItem in + Dataset and their annotations in specified annotated + dataset will be exported. It's in format of + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + + This corresponds to the ``annotated_dataset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + output_config (:class:`google.cloud.datalabeling_v1beta1.types.OutputConfig`): + Required. Specify the output + destination. + + This corresponds to the ``output_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.datalabeling_v1beta1.types.ExportDataOperationResponse` + Response used for ExportDataset longrunning operation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, annotated_dataset, filter, output_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 = data_labeling_service.ExportDataRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if annotated_dataset is not None: + request.annotated_dataset = annotated_dataset + if filter is not None: + request.filter = filter + if output_config is not None: + request.output_config = output_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.export_data, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + operations.ExportDataOperationResponse, + metadata_type=operations.ExportDataOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_data_item(self, + request: data_labeling_service.GetDataItemRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.DataItem: + r"""Gets a data item in a dataset by resource name. This + API can be called after data are imported into dataset. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetDataItemRequest`): + The request object. Request message for GetDataItem. + name (:class:`str`): + Required. The name of the data item to get, format: + projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} + + 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.datalabeling_v1beta1.types.DataItem: + DataItem is a piece of data, without + annotation. For example, an image. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.GetDataItemRequest(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_data_item, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_data_items(self, + request: data_labeling_service.ListDataItemsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataItemsAsyncPager: + r"""Lists data items in a dataset. This API can be called + after data are imported into dataset. Pagination is + supported. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsRequest`): + The request object. Request message for ListDataItems. + parent (:class:`str`): + Required. Name of the dataset to list data items, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDataItemsAsyncPager: + Results of listing data items in a + dataset. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.ListDataItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_data_items, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataItemsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_annotated_dataset(self, + request: data_labeling_service.GetAnnotatedDatasetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.AnnotatedDataset: + r"""Gets an annotated dataset by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetAnnotatedDatasetRequest`): + The request object. Request message for + GetAnnotatedDataset. + name (:class:`str`): + Required. Name of the annotated dataset to get, format: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + + 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.datalabeling_v1beta1.types.AnnotatedDataset: + AnnotatedDataset is a set holding + annotations for data in a Dataset. Each + labeling task will generate an + AnnotatedDataset under the Dataset that + the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.GetAnnotatedDatasetRequest(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_annotated_dataset, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_annotated_datasets(self, + request: data_labeling_service.ListAnnotatedDatasetsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotatedDatasetsAsyncPager: + r"""Lists annotated datasets for a dataset. Pagination is + supported. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest`): + The request object. Request message for + ListAnnotatedDatasets. + parent (:class:`str`): + Required. Name of the dataset to list annotated + datasets, format: + projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotatedDatasetsAsyncPager: + Results of listing annotated datasets + for a dataset. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.ListAnnotatedDatasetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_annotated_datasets, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAnnotatedDatasetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_annotated_dataset(self, + request: data_labeling_service.DeleteAnnotatedDatasetRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an annotated dataset by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteAnnotatedDatasetRequest`): + The request object. Request message for + DeleteAnnotatedDataset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = data_labeling_service.DeleteAnnotatedDatasetRequest(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.delete_annotated_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(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def label_image(self, + request: data_labeling_service.LabelImageRequest = None, + *, + parent: str = None, + basic_config: human_annotation_config.HumanAnnotationConfig = None, + feature: data_labeling_service.LabelImageRequest.Feature = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a labeling task for image. The type of image + labeling task is configured by feature in the request. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.LabelImageRequest`): + The request object. Request message for starting an + image labeling task. + parent (:class:`str`): + Required. Name of the dataset to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + basic_config (:class:`google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig`): + Required. Basic human annotation + config. + + This corresponds to the ``basic_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature (:class:`google.cloud.datalabeling_v1beta1.types.LabelImageRequest.Feature`): + Required. The type of image labeling + task. + + This corresponds to the ``feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each + labeling task will generate an AnnotatedDataset under + the Dataset that the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, basic_config, feature]) + if request is 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 = data_labeling_service.LabelImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if basic_config is not None: + request.basic_config = basic_config + if feature is not None: + request.feature = feature + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.label_image, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dataset.AnnotatedDataset, + metadata_type=operations.LabelOperationMetadata, + ) + + # Done; return the response. + return response + + async def label_video(self, + request: data_labeling_service.LabelVideoRequest = None, + *, + parent: str = None, + basic_config: human_annotation_config.HumanAnnotationConfig = None, + feature: data_labeling_service.LabelVideoRequest.Feature = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a labeling task for video. The type of video + labeling task is configured by feature in the request. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.LabelVideoRequest`): + The request object. Request message for LabelVideo. + parent (:class:`str`): + Required. Name of the dataset to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + basic_config (:class:`google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig`): + Required. Basic human annotation + config. + + This corresponds to the ``basic_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature (:class:`google.cloud.datalabeling_v1beta1.types.LabelVideoRequest.Feature`): + Required. The type of video labeling + task. + + This corresponds to the ``feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each + labeling task will generate an AnnotatedDataset under + the Dataset that the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, basic_config, feature]) + if request is 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 = data_labeling_service.LabelVideoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if basic_config is not None: + request.basic_config = basic_config + if feature is not None: + request.feature = feature + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.label_video, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dataset.AnnotatedDataset, + metadata_type=operations.LabelOperationMetadata, + ) + + # Done; return the response. + return response + + async def label_text(self, + request: data_labeling_service.LabelTextRequest = None, + *, + parent: str = None, + basic_config: human_annotation_config.HumanAnnotationConfig = None, + feature: data_labeling_service.LabelTextRequest.Feature = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a labeling task for text. The type of text + labeling task is configured by feature in the request. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.LabelTextRequest`): + The request object. Request message for LabelText. + parent (:class:`str`): + Required. Name of the data set to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + basic_config (:class:`google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig`): + Required. Basic human annotation + config. + + This corresponds to the ``basic_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature (:class:`google.cloud.datalabeling_v1beta1.types.LabelTextRequest.Feature`): + Required. The type of text labeling + task. + + This corresponds to the ``feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each + labeling task will generate an AnnotatedDataset under + the Dataset that the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, basic_config, feature]) + if request is 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 = data_labeling_service.LabelTextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if basic_config is not None: + request.basic_config = basic_config + if feature is not None: + request.feature = feature + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.label_text, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dataset.AnnotatedDataset, + metadata_type=operations.LabelOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_example(self, + request: data_labeling_service.GetExampleRequest = None, + *, + name: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.Example: + r"""Gets an example by resource name, including both data + and annotation. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetExampleRequest`): + The request object. Request message for GetExample + name (:class:`str`): + Required. Name of example, format: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id}/examples/{example_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. An expression for filtering Examples. Filter + by annotation_spec.display_name is supported. Format + "annotation_spec.display_name = {display_name}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.Example: + An Example is a piece of data and its + annotation. For example, an image with + label "house". + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.GetExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if filter is not None: + request.filter = filter + + # 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_example, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_examples(self, + request: data_labeling_service.ListExamplesRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExamplesAsyncPager: + r"""Lists examples in an annotated dataset. Pagination is + supported. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ListExamplesRequest`): + The request object. Request message for ListExamples. + parent (:class:`str`): + Required. Example resource parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. An expression for filtering Examples. For + annotated datasets that have annotation spec set, filter + by annotation_spec.display_name is supported. Format + "annotation_spec.display_name = {display_name}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListExamplesAsyncPager: + Results of listing Examples in and + annotated dataset. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.ListExamplesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_examples, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListExamplesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_annotation_spec_set(self, + request: data_labeling_service.CreateAnnotationSpecSetRequest = None, + *, + parent: str = None, + annotation_spec_set: gcd_annotation_spec_set.AnnotationSpecSet = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_annotation_spec_set.AnnotationSpecSet: + r"""Creates an annotation spec set by providing a set of + labels. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.CreateAnnotationSpecSetRequest`): + The request object. Request message for + CreateAnnotationSpecSet. + parent (:class:`str`): + Required. AnnotationSpecSet resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation_spec_set (:class:`google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet`): + Required. Annotation spec set to create. Annotation + specs must be included. Only one annotation spec will be + accepted for annotation specs with same display_name. + + This corresponds to the ``annotation_spec_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotationSpecSet: + An AnnotationSpecSet is a collection + of label definitions. For example, in + image classification tasks, you define a + set of possible labels for images as an + AnnotationSpecSet. An AnnotationSpecSet + is immutable upon creation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, annotation_spec_set]) + if request is 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 = data_labeling_service.CreateAnnotationSpecSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if annotation_spec_set is not None: + request.annotation_spec_set = annotation_spec_set + + # 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_annotation_spec_set, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_annotation_spec_set(self, + request: data_labeling_service.GetAnnotationSpecSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> annotation_spec_set.AnnotationSpecSet: + r"""Gets an annotation spec set by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetAnnotationSpecSetRequest`): + The request object. Request message for + GetAnnotationSpecSet. + name (:class:`str`): + Required. AnnotationSpecSet resource name, format: + projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} + + 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.datalabeling_v1beta1.types.AnnotationSpecSet: + An AnnotationSpecSet is a collection + of label definitions. For example, in + image classification tasks, you define a + set of possible labels for images as an + AnnotationSpecSet. An AnnotationSpecSet + is immutable upon creation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.GetAnnotationSpecSetRequest(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_annotation_spec_set, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_annotation_spec_sets(self, + request: data_labeling_service.ListAnnotationSpecSetsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotationSpecSetsAsyncPager: + r"""Lists annotation spec sets for a project. Pagination + is supported. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest`): + The request object. Request message for + ListAnnotationSpecSets. + parent (:class:`str`): + Required. Parent of AnnotationSpecSet resource, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotationSpecSetsAsyncPager: + Results of listing annotation spec + set under a project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.ListAnnotationSpecSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_annotation_spec_sets, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAnnotationSpecSetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_annotation_spec_set(self, + request: data_labeling_service.DeleteAnnotationSpecSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an annotation spec set by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteAnnotationSpecSetRequest`): + The request object. Request message for + DeleteAnnotationSpecSet. + name (:class:`str`): + Required. AnnotationSpec resource name, format: + ``projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}``. + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.DeleteAnnotationSpecSetRequest(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_annotation_spec_set, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_instruction(self, + request: data_labeling_service.CreateInstructionRequest = None, + *, + parent: str = None, + instruction: gcd_instruction.Instruction = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an instruction for how data should be + labeled. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.CreateInstructionRequest`): + The request object. Request message for + CreateInstruction. + parent (:class:`str`): + Required. Instruction resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instruction (:class:`google.cloud.datalabeling_v1beta1.types.Instruction`): + Required. Instruction of how to + perform the labeling task. + + This corresponds to the ``instruction`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.Instruction` Instruction of how to perform the labeling task for human operators. + Currently only PDF instruction is supported. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, instruction]) + if request is 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 = data_labeling_service.CreateInstructionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instruction is not None: + request.instruction = instruction + + # 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_instruction, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_instruction.Instruction, + metadata_type=operations.CreateInstructionMetadata, + ) + + # Done; return the response. + return response + + async def get_instruction(self, + request: data_labeling_service.GetInstructionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instruction.Instruction: + r"""Gets an instruction by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetInstructionRequest`): + The request object. Request message for GetInstruction. + name (:class:`str`): + Required. Instruction resource name, format: + projects/{project_id}/instructions/{instruction_id} + + 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.datalabeling_v1beta1.types.Instruction: + Instruction of how to perform the + labeling task for human operators. + Currently only PDF instruction is + supported. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.GetInstructionRequest(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_instruction, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_instructions(self, + request: data_labeling_service.ListInstructionsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstructionsAsyncPager: + r"""Lists instructions for a project. Pagination is + supported. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsRequest`): + The request object. Request message for + ListInstructions. + parent (:class:`str`): + Required. Instruction resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListInstructionsAsyncPager: + Results of listing instructions under + a project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.ListInstructionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_instructions, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListInstructionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_instruction(self, + request: data_labeling_service.DeleteInstructionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an instruction object by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteInstructionRequest`): + The request object. Request message for + DeleteInstruction. + name (:class:`str`): + Required. Instruction resource name, format: + projects/{project_id}/instructions/{instruction_id} + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.DeleteInstructionRequest(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_instruction, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_evaluation(self, + request: data_labeling_service.GetEvaluationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Gets an evaluation by resource name (to search, use + [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetEvaluationRequest`): + The request object. Request message for GetEvaluation. + name (:class:`str`): + Required. Name of the evaluation. Format: + + "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' + + 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.datalabeling_v1beta1.types.Evaluation: + Describes an evaluation between a machine learning model's predictions and + ground truth labels. Created when an + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] + runs successfully. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_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_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_evaluations(self, + request: data_labeling_service.SearchEvaluationsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchEvaluationsAsyncPager: + r"""Searches + [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] + within a project. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsRequest`): + The request object. Request message for + SearchEvaluation. + parent (:class:`str`): + Required. Evaluation search parent (project ID). Format: + "projects/{project_id}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. To search evaluations, you can filter by the + following: + + - evaluation\_job.evaluation_job_id (the last part of + [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) + - evaluation\_job.model_id (the {model_name} portion of + [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) + - evaluation\_job.evaluation_job_run_time_start + (Minimum threshold for the + [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] + that created the evaluation) + - evaluation\_job.evaluation_job_run_time_end (Maximum + threshold for the + [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] + that created the evaluation) + - evaluation\_job.job_state + ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) + - annotation\_spec.display_name (the Evaluation + contains a metric for the annotation spec with this + [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) + + To filter by multiple critiera, use the ``AND`` operator + or the ``OR`` operator. The following examples shows a + string that filters by several critiera: + + "evaluation\ *job.evaluation_job_id = + {evaluation_job_id} AND evaluation*\ job.model_id = + {model_name} AND + evaluation\ *job.evaluation_job_run_time_start = + {timestamp_1} AND + evaluation*\ job.evaluation_job_run_time_end = + {timestamp_2} AND annotation\_spec.display_name = + {display_name}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchEvaluationsAsyncPager: + Results of searching evaluations. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.SearchEvaluationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_evaluations, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchEvaluationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_example_comparisons(self, + request: data_labeling_service.SearchExampleComparisonsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchExampleComparisonsAsyncPager: + r"""Searches example comparisons from an evaluation. The + return format is a list of example comparisons that show + ground truth and prediction(s) for a single input. + Search by providing an evaluation ID. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsRequest`): + The request object. Request message of + SearchExampleComparisons. + parent (:class:`str`): + Required. Name of the + [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] + resource to search for example comparisons from. Format: + + "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}" + + 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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchExampleComparisonsAsyncPager: + Results of searching example + comparisons. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.SearchExampleComparisonsRequest(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.search_example_comparisons, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchExampleComparisonsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_evaluation_job(self, + request: data_labeling_service.CreateEvaluationJobRequest = None, + *, + parent: str = None, + job: evaluation_job.EvaluationJob = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_job.EvaluationJob: + r"""Creates an evaluation job. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.CreateEvaluationJobRequest`): + The request object. Request message for + CreateEvaluationJob. + parent (:class:`str`): + Required. Evaluation job resource parent. Format: + "projects/{project_id}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + job (:class:`google.cloud.datalabeling_v1beta1.types.EvaluationJob`): + Required. The evaluation job to + create. + + This corresponds to the ``job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.EvaluationJob: + Defines an evaluation job that runs periodically to generate + [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. + [Creating an evaluation + job](/ml-engine/docs/continuous-evaluation/create-job) + is the starting point for using continuous + evaluation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, job]) + if request is 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 = data_labeling_service.CreateEvaluationJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if job is not None: + request.job = job + + # 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_evaluation_job, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_evaluation_job(self, + request: data_labeling_service.UpdateEvaluationJobRequest = None, + *, + evaluation_job: gcd_evaluation_job.EvaluationJob = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_evaluation_job.EvaluationJob: + r"""Updates an evaluation job. You can only update certain fields of + the job's + [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: + ``humanAnnotationConfig.instruction``, ``exampleCount``, and + ``exampleSamplePercentage``. + + If you want to change any other aspect of the evaluation job, + you must delete the job and create a new one. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.UpdateEvaluationJobRequest`): + The request object. Request message for + UpdateEvaluationJob. + evaluation_job (:class:`google.cloud.datalabeling_v1beta1.types.EvaluationJob`): + Required. Evaluation job that is + going to be updated. + + This corresponds to the ``evaluation_job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Mask for which fields to update. You can only + provide the following fields: + + - ``evaluationJobConfig.humanAnnotationConfig.instruction`` + - ``evaluationJobConfig.exampleCount`` + - ``evaluationJobConfig.exampleSamplePercentage`` + + You can provide more than one of these fields by + separating them with commas. + + 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.datalabeling_v1beta1.types.EvaluationJob: + Defines an evaluation job that runs periodically to generate + [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. + [Creating an evaluation + job](/ml-engine/docs/continuous-evaluation/create-job) + is the starting point for using continuous + evaluation. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([evaluation_job, 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 = data_labeling_service.UpdateEvaluationJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation_job is not None: + request.evaluation_job = evaluation_job + 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_evaluation_job, + default_timeout=30.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(( + ("evaluation_job.name", request.evaluation_job.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_evaluation_job(self, + request: data_labeling_service.GetEvaluationJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_job.EvaluationJob: + r"""Gets an evaluation job by resource name. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.GetEvaluationJobRequest`): + The request object. Request message for + GetEvaluationJob. + name (:class:`str`): + Required. Name of the evaluation job. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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.datalabeling_v1beta1.types.EvaluationJob: + Defines an evaluation job that runs periodically to generate + [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. + [Creating an evaluation + job](/ml-engine/docs/continuous-evaluation/create-job) + is the starting point for using continuous + evaluation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.GetEvaluationJobRequest(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_job, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def pause_evaluation_job(self, + request: data_labeling_service.PauseEvaluationJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Pauses an evaluation job. Pausing an evaluation job that is + already in a ``PAUSED`` state is a no-op. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.PauseEvaluationJobRequest`): + The request object. Request message for + PauseEvaluationJob. + name (:class:`str`): + Required. Name of the evaluation job that is going to be + paused. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.PauseEvaluationJobRequest(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.pause_evaluation_job, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def resume_evaluation_job(self, + request: data_labeling_service.ResumeEvaluationJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Resumes a paused evaluation job. A deleted evaluation + job can't be resumed. Resuming a running or scheduled + evaluation job is a no-op. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ResumeEvaluationJobRequest`): + The request object. Request message ResumeEvaluationJob. + name (:class:`str`): + Required. Name of the evaluation job that is going to be + resumed. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.ResumeEvaluationJobRequest(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.resume_evaluation_job, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_evaluation_job(self, + request: data_labeling_service.DeleteEvaluationJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Stops and deletes an evaluation job. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteEvaluationJobRequest`): + The request object. Request message DeleteEvaluationJob. + name (:class:`str`): + Required. Name of the evaluation job that is going to be + deleted. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = data_labeling_service.DeleteEvaluationJobRequest(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_evaluation_job, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_evaluation_jobs(self, + request: data_labeling_service.ListEvaluationJobsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationJobsAsyncPager: + r"""Lists all evaluation jobs within a project with + possible filters. Pagination is supported. + + Args: + request (:class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsRequest`): + The request object. Request message for + ListEvaluationJobs. + parent (:class:`str`): + Required. Evaluation job resource parent. Format: + "projects/{project_id}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. You can filter the jobs to list by model_id + (also known as model_name, as described in + [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) + or by evaluation job state (as described in + [EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]). + To filter by both criteria, use the ``AND`` operator or + the ``OR`` operator. For example, you can use the + following string for your filter: + "evaluation\ *job.model_id = {model_name} AND + evaluation*\ job.state = {evaluation_job_state}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListEvaluationJobsAsyncPager: + Results for listing evaluation jobs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 = data_labeling_service.ListEvaluationJobsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_evaluation_jobs, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationJobsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datalabeling", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataLabelingServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py new file mode 100644 index 0000000..00f6ba7 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py @@ -0,0 +1,3451 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.datalabeling_v1beta1.services.data_labeling_service import pagers +from google.cloud.datalabeling_v1beta1.types import annotation +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import data_labeling_service +from google.cloud.datalabeling_v1beta1.types import data_payloads +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job +from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job +from google.cloud.datalabeling_v1beta1.types import human_annotation_config +from google.cloud.datalabeling_v1beta1.types import instruction +from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction +from google.cloud.datalabeling_v1beta1.types import operations +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataLabelingServiceGrpcTransport +from .transports.grpc_asyncio import DataLabelingServiceGrpcAsyncIOTransport + + +class DataLabelingServiceClientMeta(type): + """Metaclass for the DataLabelingService 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[DataLabelingServiceTransport]] + _transport_registry["grpc"] = DataLabelingServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DataLabelingServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DataLabelingServiceTransport]: + """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 DataLabelingServiceClient(metaclass=DataLabelingServiceClientMeta): + """Service for the AI Platform Data Labeling API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "datalabeling.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DataLabelingServiceClient: 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: + DataLabelingServiceClient: 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) -> DataLabelingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataLabelingServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def annotated_dataset_path(project: str,dataset: str,annotated_dataset: str,) -> str: + """Returns a fully-qualified annotated_dataset string.""" + return "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, ) + + @staticmethod + def parse_annotated_dataset_path(path: str) -> Dict[str,str]: + """Parses a annotated_dataset path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)/annotatedDatasets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def annotation_spec_set_path(project: str,annotation_spec_set: str,) -> str: + """Returns a fully-qualified annotation_spec_set string.""" + return "projects/{project}/annotationSpecSets/{annotation_spec_set}".format(project=project, annotation_spec_set=annotation_spec_set, ) + + @staticmethod + def parse_annotation_spec_set_path(path: str) -> Dict[str,str]: + """Parses a annotation_spec_set path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/annotationSpecSets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_item_path(project: str,dataset: str,data_item: str,) -> str: + """Returns a fully-qualified data_item string.""" + return "projects/{project}/datasets/{dataset}/dataItems/{data_item}".format(project=project, dataset=dataset, data_item=data_item, ) + + @staticmethod + def parse_data_item_path(path: str) -> Dict[str,str]: + """Parses a data_item path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)/dataItems/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def dataset_path(project: str,dataset: str,) -> str: + """Returns a fully-qualified dataset string.""" + return "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) + + @staticmethod + def parse_dataset_path(path: str) -> Dict[str,str]: + """Parses a dataset path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def evaluation_path(project: str,dataset: str,evaluation: str,) -> str: + """Returns a fully-qualified evaluation string.""" + return "projects/{project}/datasets/{dataset}/evaluations/{evaluation}".format(project=project, dataset=dataset, 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.+?)/datasets/(?P.+?)/evaluations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def evaluation_job_path(project: str,evaluation_job: str,) -> str: + """Returns a fully-qualified evaluation_job string.""" + return "projects/{project}/evaluationJobs/{evaluation_job}".format(project=project, evaluation_job=evaluation_job, ) + + @staticmethod + def parse_evaluation_job_path(path: str) -> Dict[str,str]: + """Parses a evaluation_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/evaluationJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def example_path(project: str,dataset: str,annotated_dataset: str,example: str,) -> str: + """Returns a fully-qualified example string.""" + return "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, ) + + @staticmethod + def parse_example_path(path: str) -> Dict[str,str]: + """Parses a example path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)/annotatedDatasets/(?P.+?)/examples/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def instruction_path(project: str,instruction: str,) -> str: + """Returns a fully-qualified instruction string.""" + return "projects/{project}/instructions/{instruction}".format(project=project, instruction=instruction, ) + + @staticmethod + def parse_instruction_path(path: str) -> Dict[str,str]: + """Parses a instruction path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/instructions/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataLabelingServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data labeling 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, DataLabelingServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DataLabelingServiceTransport): + # transport is a DataLabelingServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_dataset(self, + request: Union[data_labeling_service.CreateDatasetRequest, dict] = None, + *, + parent: str = None, + dataset: gcd_dataset.Dataset = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_dataset.Dataset: + r"""Creates dataset. If success return a Dataset + resource. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.CreateDatasetRequest, dict]): + The request object. Request message for CreateDataset. + parent (str): + Required. Dataset resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dataset (google.cloud.datalabeling_v1beta1.types.Dataset): + Required. The dataset to be created. + 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.datalabeling_v1beta1.types.Dataset: + Dataset is the resource to hold your + data. You can request multiple labeling + tasks for a dataset while each one will + generate an AnnotatedDataset. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, 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 data_labeling_service.CreateDatasetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.CreateDatasetRequest): + request = data_labeling_service.CreateDatasetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + 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.create_dataset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_dataset(self, + request: Union[data_labeling_service.GetDatasetRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.Dataset: + r"""Gets dataset by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetDatasetRequest, dict]): + The request object. Request message for GetDataSet. + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + 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.datalabeling_v1beta1.types.Dataset: + Dataset is the resource to hold your + data. You can request multiple labeling + tasks for a dataset while each one will + generate an AnnotatedDataset. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.GetDatasetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetDatasetRequest): + request = data_labeling_service.GetDatasetRequest(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] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_datasets(self, + request: Union[data_labeling_service.ListDatasetsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDatasetsPager: + r"""Lists datasets under a project. Pagination is + supported. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ListDatasetsRequest, dict]): + The request object. Request message for ListDataset. + parent (str): + Required. Dataset resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filter on dataset is not + supported at this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDatasetsPager: + Results of listing datasets within a + project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.ListDatasetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ListDatasetsRequest): + request = data_labeling_service.ListDatasetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_datasets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDatasetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_dataset(self, + request: Union[data_labeling_service.DeleteDatasetRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a dataset by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.DeleteDatasetRequest, dict]): + The request object. Request message for DeleteDataset. + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.DeleteDatasetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.DeleteDatasetRequest): + request = data_labeling_service.DeleteDatasetRequest(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_dataset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_data(self, + request: Union[data_labeling_service.ImportDataRequest, dict] = None, + *, + name: str = None, + input_config: dataset.InputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports data into dataset based on source locations + defined in request. It can be called multiple times for + the same dataset. Each dataset can only have one long + running operation running on it. For example, no + labeling task (also long running operation) can be + started while importing is still ongoing. Vice versa. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ImportDataRequest, dict]): + The request object. Request message for ImportData API. + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (google.cloud.datalabeling_v1beta1.types.InputConfig): + Required. Specify the input source of + the data. + + This corresponds to the ``input_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.datalabeling_v1beta1.types.ImportDataOperationResponse` + Response used for ImportData longrunning operation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, input_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 data_labeling_service.ImportDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ImportDataRequest): + request = data_labeling_service.ImportDataRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if input_config is not None: + request.input_config = input_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + operations.ImportDataOperationResponse, + metadata_type=operations.ImportDataOperationMetadata, + ) + + # Done; return the response. + return response + + def export_data(self, + request: Union[data_labeling_service.ExportDataRequest, dict] = None, + *, + name: str = None, + annotated_dataset: str = None, + filter: str = None, + output_config: dataset.OutputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports data and annotations from dataset. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ExportDataRequest, dict]): + The request object. Request message for ExportData API. + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotated_dataset (str): + Required. Annotated dataset resource name. DataItem in + Dataset and their annotations in specified annotated + dataset will be exported. It's in format of + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + + This corresponds to the ``annotated_dataset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + output_config (google.cloud.datalabeling_v1beta1.types.OutputConfig): + Required. Specify the output + destination. + + This corresponds to the ``output_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.datalabeling_v1beta1.types.ExportDataOperationResponse` + Response used for ExportDataset longrunning operation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, annotated_dataset, filter, output_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 data_labeling_service.ExportDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ExportDataRequest): + request = data_labeling_service.ExportDataRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if annotated_dataset is not None: + request.annotated_dataset = annotated_dataset + if filter is not None: + request.filter = filter + if output_config is not None: + request.output_config = output_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + operations.ExportDataOperationResponse, + metadata_type=operations.ExportDataOperationMetadata, + ) + + # Done; return the response. + return response + + def get_data_item(self, + request: Union[data_labeling_service.GetDataItemRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.DataItem: + r"""Gets a data item in a dataset by resource name. This + API can be called after data are imported into dataset. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetDataItemRequest, dict]): + The request object. Request message for GetDataItem. + name (str): + Required. The name of the data item to get, format: + projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} + + 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.datalabeling_v1beta1.types.DataItem: + DataItem is a piece of data, without + annotation. For example, an image. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.GetDataItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetDataItemRequest): + request = data_labeling_service.GetDataItemRequest(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_data_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_data_items(self, + request: Union[data_labeling_service.ListDataItemsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataItemsPager: + r"""Lists data items in a dataset. This API can be called + after data are imported into dataset. Pagination is + supported. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ListDataItemsRequest, dict]): + The request object. Request message for ListDataItems. + parent (str): + Required. Name of the dataset to list data items, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDataItemsPager: + Results of listing data items in a + dataset. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.ListDataItemsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ListDataItemsRequest): + request = data_labeling_service.ListDataItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_data_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataItemsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_annotated_dataset(self, + request: Union[data_labeling_service.GetAnnotatedDatasetRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.AnnotatedDataset: + r"""Gets an annotated dataset by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetAnnotatedDatasetRequest, dict]): + The request object. Request message for + GetAnnotatedDataset. + name (str): + Required. Name of the annotated dataset to get, format: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + + 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.datalabeling_v1beta1.types.AnnotatedDataset: + AnnotatedDataset is a set holding + annotations for data in a Dataset. Each + labeling task will generate an + AnnotatedDataset under the Dataset that + the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.GetAnnotatedDatasetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetAnnotatedDatasetRequest): + request = data_labeling_service.GetAnnotatedDatasetRequest(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_annotated_dataset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_annotated_datasets(self, + request: Union[data_labeling_service.ListAnnotatedDatasetsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotatedDatasetsPager: + r"""Lists annotated datasets for a dataset. Pagination is + supported. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest, dict]): + The request object. Request message for + ListAnnotatedDatasets. + parent (str): + Required. Name of the dataset to list annotated + datasets, format: + projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotatedDatasetsPager: + Results of listing annotated datasets + for a dataset. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.ListAnnotatedDatasetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ListAnnotatedDatasetsRequest): + request = data_labeling_service.ListAnnotatedDatasetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_annotated_datasets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAnnotatedDatasetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_annotated_dataset(self, + request: Union[data_labeling_service.DeleteAnnotatedDatasetRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an annotated dataset by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.DeleteAnnotatedDatasetRequest, dict]): + The request object. Request message for + DeleteAnnotatedDataset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a data_labeling_service.DeleteAnnotatedDatasetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.DeleteAnnotatedDatasetRequest): + request = data_labeling_service.DeleteAnnotatedDatasetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_annotated_dataset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def label_image(self, + request: Union[data_labeling_service.LabelImageRequest, dict] = None, + *, + parent: str = None, + basic_config: human_annotation_config.HumanAnnotationConfig = None, + feature: data_labeling_service.LabelImageRequest.Feature = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a labeling task for image. The type of image + labeling task is configured by feature in the request. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.LabelImageRequest, dict]): + The request object. Request message for starting an + image labeling task. + parent (str): + Required. Name of the dataset to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Required. Basic human annotation + config. + + This corresponds to the ``basic_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature (google.cloud.datalabeling_v1beta1.types.LabelImageRequest.Feature): + Required. The type of image labeling + task. + + This corresponds to the ``feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each + labeling task will generate an AnnotatedDataset under + the Dataset that the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, basic_config, feature]) + if request is 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 data_labeling_service.LabelImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.LabelImageRequest): + request = data_labeling_service.LabelImageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if basic_config is not None: + request.basic_config = basic_config + if feature is not None: + request.feature = feature + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.label_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dataset.AnnotatedDataset, + metadata_type=operations.LabelOperationMetadata, + ) + + # Done; return the response. + return response + + def label_video(self, + request: Union[data_labeling_service.LabelVideoRequest, dict] = None, + *, + parent: str = None, + basic_config: human_annotation_config.HumanAnnotationConfig = None, + feature: data_labeling_service.LabelVideoRequest.Feature = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a labeling task for video. The type of video + labeling task is configured by feature in the request. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.LabelVideoRequest, dict]): + The request object. Request message for LabelVideo. + parent (str): + Required. Name of the dataset to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Required. Basic human annotation + config. + + This corresponds to the ``basic_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature (google.cloud.datalabeling_v1beta1.types.LabelVideoRequest.Feature): + Required. The type of video labeling + task. + + This corresponds to the ``feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each + labeling task will generate an AnnotatedDataset under + the Dataset that the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, basic_config, feature]) + if request is 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 data_labeling_service.LabelVideoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.LabelVideoRequest): + request = data_labeling_service.LabelVideoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if basic_config is not None: + request.basic_config = basic_config + if feature is not None: + request.feature = feature + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.label_video] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dataset.AnnotatedDataset, + metadata_type=operations.LabelOperationMetadata, + ) + + # Done; return the response. + return response + + def label_text(self, + request: Union[data_labeling_service.LabelTextRequest, dict] = None, + *, + parent: str = None, + basic_config: human_annotation_config.HumanAnnotationConfig = None, + feature: data_labeling_service.LabelTextRequest.Feature = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a labeling task for text. The type of text + labeling task is configured by feature in the request. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.LabelTextRequest, dict]): + The request object. Request message for LabelText. + parent (str): + Required. Name of the data set to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Required. Basic human annotation + config. + + This corresponds to the ``basic_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature (google.cloud.datalabeling_v1beta1.types.LabelTextRequest.Feature): + Required. The type of text labeling + task. + + This corresponds to the ``feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each + labeling task will generate an AnnotatedDataset under + the Dataset that the task is requested for. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, basic_config, feature]) + if request is 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 data_labeling_service.LabelTextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.LabelTextRequest): + request = data_labeling_service.LabelTextRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if basic_config is not None: + request.basic_config = basic_config + if feature is not None: + request.feature = feature + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.label_text] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dataset.AnnotatedDataset, + metadata_type=operations.LabelOperationMetadata, + ) + + # Done; return the response. + return response + + def get_example(self, + request: Union[data_labeling_service.GetExampleRequest, dict] = None, + *, + name: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dataset.Example: + r"""Gets an example by resource name, including both data + and annotation. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetExampleRequest, dict]): + The request object. Request message for GetExample + name (str): + Required. Name of example, format: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id}/examples/{example_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. An expression for filtering Examples. Filter + by annotation_spec.display_name is supported. Format + "annotation_spec.display_name = {display_name}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.Example: + An Example is a piece of data and its + annotation. For example, an image with + label "house". + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.GetExampleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetExampleRequest): + request = data_labeling_service.GetExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_examples(self, + request: Union[data_labeling_service.ListExamplesRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExamplesPager: + r"""Lists examples in an annotated dataset. Pagination is + supported. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ListExamplesRequest, dict]): + The request object. Request message for ListExamples. + parent (str): + Required. Example resource parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. An expression for filtering Examples. For + annotated datasets that have annotation spec set, filter + by annotation_spec.display_name is supported. Format + "annotation_spec.display_name = {display_name}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListExamplesPager: + Results of listing Examples in and + annotated dataset. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.ListExamplesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ListExamplesRequest): + request = data_labeling_service.ListExamplesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_examples] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListExamplesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_annotation_spec_set(self, + request: Union[data_labeling_service.CreateAnnotationSpecSetRequest, dict] = None, + *, + parent: str = None, + annotation_spec_set: gcd_annotation_spec_set.AnnotationSpecSet = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_annotation_spec_set.AnnotationSpecSet: + r"""Creates an annotation spec set by providing a set of + labels. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.CreateAnnotationSpecSetRequest, dict]): + The request object. Request message for + CreateAnnotationSpecSet. + parent (str): + Required. AnnotationSpecSet resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation_spec_set (google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet): + Required. Annotation spec set to create. Annotation + specs must be included. Only one annotation spec will be + accepted for annotation specs with same display_name. + + This corresponds to the ``annotation_spec_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.AnnotationSpecSet: + An AnnotationSpecSet is a collection + of label definitions. For example, in + image classification tasks, you define a + set of possible labels for images as an + AnnotationSpecSet. An AnnotationSpecSet + is immutable upon creation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, annotation_spec_set]) + if request is 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 data_labeling_service.CreateAnnotationSpecSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.CreateAnnotationSpecSetRequest): + request = data_labeling_service.CreateAnnotationSpecSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if annotation_spec_set is not None: + request.annotation_spec_set = annotation_spec_set + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_annotation_spec_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_annotation_spec_set(self, + request: Union[data_labeling_service.GetAnnotationSpecSetRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> annotation_spec_set.AnnotationSpecSet: + r"""Gets an annotation spec set by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetAnnotationSpecSetRequest, dict]): + The request object. Request message for + GetAnnotationSpecSet. + name (str): + Required. AnnotationSpecSet resource name, format: + projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} + + 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.datalabeling_v1beta1.types.AnnotationSpecSet: + An AnnotationSpecSet is a collection + of label definitions. For example, in + image classification tasks, you define a + set of possible labels for images as an + AnnotationSpecSet. An AnnotationSpecSet + is immutable upon creation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.GetAnnotationSpecSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetAnnotationSpecSetRequest): + request = data_labeling_service.GetAnnotationSpecSetRequest(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_annotation_spec_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_annotation_spec_sets(self, + request: Union[data_labeling_service.ListAnnotationSpecSetsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotationSpecSetsPager: + r"""Lists annotation spec sets for a project. Pagination + is supported. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest, dict]): + The request object. Request message for + ListAnnotationSpecSets. + parent (str): + Required. Parent of AnnotationSpecSet resource, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotationSpecSetsPager: + Results of listing annotation spec + set under a project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.ListAnnotationSpecSetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ListAnnotationSpecSetsRequest): + request = data_labeling_service.ListAnnotationSpecSetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_annotation_spec_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAnnotationSpecSetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_annotation_spec_set(self, + request: Union[data_labeling_service.DeleteAnnotationSpecSetRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an annotation spec set by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.DeleteAnnotationSpecSetRequest, dict]): + The request object. Request message for + DeleteAnnotationSpecSet. + name (str): + Required. AnnotationSpec resource name, format: + ``projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}``. + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.DeleteAnnotationSpecSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.DeleteAnnotationSpecSetRequest): + request = data_labeling_service.DeleteAnnotationSpecSetRequest(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_annotation_spec_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_instruction(self, + request: Union[data_labeling_service.CreateInstructionRequest, dict] = None, + *, + parent: str = None, + instruction: gcd_instruction.Instruction = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates an instruction for how data should be + labeled. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.CreateInstructionRequest, dict]): + The request object. Request message for + CreateInstruction. + parent (str): + Required. Instruction resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instruction (google.cloud.datalabeling_v1beta1.types.Instruction): + Required. Instruction of how to + perform the labeling task. + + This corresponds to the ``instruction`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.Instruction` Instruction of how to perform the labeling task for human operators. + Currently only PDF instruction is supported. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, instruction]) + if request is 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 data_labeling_service.CreateInstructionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.CreateInstructionRequest): + request = data_labeling_service.CreateInstructionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instruction is not None: + request.instruction = instruction + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_instruction] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_instruction.Instruction, + metadata_type=operations.CreateInstructionMetadata, + ) + + # Done; return the response. + return response + + def get_instruction(self, + request: Union[data_labeling_service.GetInstructionRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instruction.Instruction: + r"""Gets an instruction by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetInstructionRequest, dict]): + The request object. Request message for GetInstruction. + name (str): + Required. Instruction resource name, format: + projects/{project_id}/instructions/{instruction_id} + + 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.datalabeling_v1beta1.types.Instruction: + Instruction of how to perform the + labeling task for human operators. + Currently only PDF instruction is + supported. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.GetInstructionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetInstructionRequest): + request = data_labeling_service.GetInstructionRequest(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_instruction] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_instructions(self, + request: Union[data_labeling_service.ListInstructionsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstructionsPager: + r"""Lists instructions for a project. Pagination is + supported. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ListInstructionsRequest, dict]): + The request object. Request message for + ListInstructions. + parent (str): + Required. Instruction resource parent, format: + projects/{project_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filter is not supported at + this moment. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListInstructionsPager: + Results of listing instructions under + a project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.ListInstructionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ListInstructionsRequest): + request = data_labeling_service.ListInstructionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_instructions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListInstructionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_instruction(self, + request: Union[data_labeling_service.DeleteInstructionRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an instruction object by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.DeleteInstructionRequest, dict]): + The request object. Request message for + DeleteInstruction. + name (str): + Required. Instruction resource name, format: + projects/{project_id}/instructions/{instruction_id} + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.DeleteInstructionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.DeleteInstructionRequest): + request = data_labeling_service.DeleteInstructionRequest(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_instruction] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_evaluation(self, + request: Union[data_labeling_service.GetEvaluationRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Gets an evaluation by resource name (to search, use + [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetEvaluationRequest, dict]): + The request object. Request message for GetEvaluation. + name (str): + Required. Name of the evaluation. Format: + + "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' + + 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.datalabeling_v1beta1.types.Evaluation: + Describes an evaluation between a machine learning model's predictions and + ground truth labels. Created when an + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] + runs successfully. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.GetEvaluationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetEvaluationRequest): + request = data_labeling_service.GetEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_evaluations(self, + request: Union[data_labeling_service.SearchEvaluationsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchEvaluationsPager: + r"""Searches + [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] + within a project. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.SearchEvaluationsRequest, dict]): + The request object. Request message for + SearchEvaluation. + parent (str): + Required. Evaluation search parent (project ID). Format: + "projects/{project_id}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. To search evaluations, you can filter by the + following: + + - evaluation\_job.evaluation_job_id (the last part of + [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) + - evaluation\_job.model_id (the {model_name} portion of + [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) + - evaluation\_job.evaluation_job_run_time_start + (Minimum threshold for the + [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] + that created the evaluation) + - evaluation\_job.evaluation_job_run_time_end (Maximum + threshold for the + [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] + that created the evaluation) + - evaluation\_job.job_state + ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) + - annotation\_spec.display_name (the Evaluation + contains a metric for the annotation spec with this + [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) + + To filter by multiple critiera, use the ``AND`` operator + or the ``OR`` operator. The following examples shows a + string that filters by several critiera: + + "evaluation\ *job.evaluation_job_id = + {evaluation_job_id} AND evaluation*\ job.model_id = + {model_name} AND + evaluation\ *job.evaluation_job_run_time_start = + {timestamp_1} AND + evaluation*\ job.evaluation_job_run_time_end = + {timestamp_2} AND annotation\_spec.display_name = + {display_name}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchEvaluationsPager: + Results of searching evaluations. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.SearchEvaluationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.SearchEvaluationsRequest): + request = data_labeling_service.SearchEvaluationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_evaluations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchEvaluationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_example_comparisons(self, + request: Union[data_labeling_service.SearchExampleComparisonsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchExampleComparisonsPager: + r"""Searches example comparisons from an evaluation. The + return format is a list of example comparisons that show + ground truth and prediction(s) for a single input. + Search by providing an evaluation ID. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsRequest, dict]): + The request object. Request message of + SearchExampleComparisons. + parent (str): + Required. Name of the + [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] + resource to search for example comparisons from. Format: + + "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}" + + 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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchExampleComparisonsPager: + Results of searching example + comparisons. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.SearchExampleComparisonsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.SearchExampleComparisonsRequest): + request = data_labeling_service.SearchExampleComparisonsRequest(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.search_example_comparisons] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchExampleComparisonsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_evaluation_job(self, + request: Union[data_labeling_service.CreateEvaluationJobRequest, dict] = None, + *, + parent: str = None, + job: evaluation_job.EvaluationJob = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_job.EvaluationJob: + r"""Creates an evaluation job. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.CreateEvaluationJobRequest, dict]): + The request object. Request message for + CreateEvaluationJob. + parent (str): + Required. Evaluation job resource parent. Format: + "projects/{project_id}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): + Required. The evaluation job to + create. + + This corresponds to the ``job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.types.EvaluationJob: + Defines an evaluation job that runs periodically to generate + [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. + [Creating an evaluation + job](/ml-engine/docs/continuous-evaluation/create-job) + is the starting point for using continuous + evaluation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, job]) + if request is 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 data_labeling_service.CreateEvaluationJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.CreateEvaluationJobRequest): + request = data_labeling_service.CreateEvaluationJobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if job is not None: + request.job = job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_evaluation_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_evaluation_job(self, + request: Union[data_labeling_service.UpdateEvaluationJobRequest, dict] = None, + *, + evaluation_job: gcd_evaluation_job.EvaluationJob = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_evaluation_job.EvaluationJob: + r"""Updates an evaluation job. You can only update certain fields of + the job's + [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: + ``humanAnnotationConfig.instruction``, ``exampleCount``, and + ``exampleSamplePercentage``. + + If you want to change any other aspect of the evaluation job, + you must delete the job and create a new one. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.UpdateEvaluationJobRequest, dict]): + The request object. Request message for + UpdateEvaluationJob. + evaluation_job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): + Required. Evaluation job that is + going to be updated. + + This corresponds to the ``evaluation_job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Mask for which fields to update. You can only + provide the following fields: + + - ``evaluationJobConfig.humanAnnotationConfig.instruction`` + - ``evaluationJobConfig.exampleCount`` + - ``evaluationJobConfig.exampleSamplePercentage`` + + You can provide more than one of these fields by + separating them with commas. + + 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.datalabeling_v1beta1.types.EvaluationJob: + Defines an evaluation job that runs periodically to generate + [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. + [Creating an evaluation + job](/ml-engine/docs/continuous-evaluation/create-job) + is the starting point for using continuous + evaluation. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([evaluation_job, 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 data_labeling_service.UpdateEvaluationJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.UpdateEvaluationJobRequest): + request = data_labeling_service.UpdateEvaluationJobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation_job is not None: + request.evaluation_job = evaluation_job + 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_evaluation_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("evaluation_job.name", request.evaluation_job.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_evaluation_job(self, + request: Union[data_labeling_service.GetEvaluationJobRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_job.EvaluationJob: + r"""Gets an evaluation job by resource name. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.GetEvaluationJobRequest, dict]): + The request object. Request message for + GetEvaluationJob. + name (str): + Required. Name of the evaluation job. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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.datalabeling_v1beta1.types.EvaluationJob: + Defines an evaluation job that runs periodically to generate + [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. + [Creating an evaluation + job](/ml-engine/docs/continuous-evaluation/create-job) + is the starting point for using continuous + evaluation. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.GetEvaluationJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.GetEvaluationJobRequest): + request = data_labeling_service.GetEvaluationJobRequest(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_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def pause_evaluation_job(self, + request: Union[data_labeling_service.PauseEvaluationJobRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Pauses an evaluation job. Pausing an evaluation job that is + already in a ``PAUSED`` state is a no-op. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.PauseEvaluationJobRequest, dict]): + The request object. Request message for + PauseEvaluationJob. + name (str): + Required. Name of the evaluation job that is going to be + paused. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.PauseEvaluationJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.PauseEvaluationJobRequest): + request = data_labeling_service.PauseEvaluationJobRequest(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.pause_evaluation_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def resume_evaluation_job(self, + request: Union[data_labeling_service.ResumeEvaluationJobRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Resumes a paused evaluation job. A deleted evaluation + job can't be resumed. Resuming a running or scheduled + evaluation job is a no-op. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ResumeEvaluationJobRequest, dict]): + The request object. Request message ResumeEvaluationJob. + name (str): + Required. Name of the evaluation job that is going to be + resumed. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.ResumeEvaluationJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ResumeEvaluationJobRequest): + request = data_labeling_service.ResumeEvaluationJobRequest(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.resume_evaluation_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def delete_evaluation_job(self, + request: Union[data_labeling_service.DeleteEvaluationJobRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Stops and deletes an evaluation job. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.DeleteEvaluationJobRequest, dict]): + The request object. Request message DeleteEvaluationJob. + name (str): + Required. Name of the evaluation job that is going to be + deleted. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}" + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 data_labeling_service.DeleteEvaluationJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.DeleteEvaluationJobRequest): + request = data_labeling_service.DeleteEvaluationJobRequest(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_evaluation_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_evaluation_jobs(self, + request: Union[data_labeling_service.ListEvaluationJobsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationJobsPager: + r"""Lists all evaluation jobs within a project with + possible filters. Pagination is supported. + + Args: + request (Union[google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsRequest, dict]): + The request object. Request message for + ListEvaluationJobs. + parent (str): + Required. Evaluation job resource parent. Format: + "projects/{project_id}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. You can filter the jobs to list by model_id + (also known as model_name, as described in + [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) + or by evaluation job state (as described in + [EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]). + To filter by both criteria, use the ``AND`` operator or + the ``OR`` operator. For example, you can use the + following string for your filter: + "evaluation\ *job.model_id = {model_name} AND + evaluation*\ job.state = {evaluation_job_state}" + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListEvaluationJobsPager: + Results for listing evaluation jobs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, filter]) + if request is 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 data_labeling_service.ListEvaluationJobsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_labeling_service.ListEvaluationJobsRequest): + request = data_labeling_service.ListEvaluationJobsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluation_jobs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationJobsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datalabeling", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataLabelingServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py new file mode 100644 index 0000000..b739a2c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py @@ -0,0 +1,1121 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.datalabeling_v1beta1.types import annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import data_labeling_service +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job +from google.cloud.datalabeling_v1beta1.types import instruction + + +class ListDatasetsPager: + """A pager for iterating through ``list_datasets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``datasets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDatasets`` requests and continue to iterate + through the ``datasets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` + 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[..., data_labeling_service.ListDatasetsResponse], + request: data_labeling_service.ListDatasetsRequest, + response: data_labeling_service.ListDatasetsResponse, + *, + 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.datalabeling_v1beta1.types.ListDatasetsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse): + 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 = data_labeling_service.ListDatasetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.ListDatasetsResponse]: + 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[dataset.Dataset]: + for page in self.pages: + yield from page.datasets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDatasetsAsyncPager: + """A pager for iterating through ``list_datasets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``datasets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDatasets`` requests and continue to iterate + through the ``datasets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` + 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[data_labeling_service.ListDatasetsResponse]], + request: data_labeling_service.ListDatasetsRequest, + response: data_labeling_service.ListDatasetsResponse, + *, + 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.datalabeling_v1beta1.types.ListDatasetsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse): + 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 = data_labeling_service.ListDatasetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.ListDatasetsResponse]: + 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[dataset.Dataset]: + async def async_generator(): + async for page in self.pages: + for response in page.datasets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataItemsPager: + """A pager for iterating through ``list_data_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataItems`` requests and continue to iterate + through the ``data_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` + 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[..., data_labeling_service.ListDataItemsResponse], + request: data_labeling_service.ListDataItemsRequest, + response: data_labeling_service.ListDataItemsResponse, + *, + 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.datalabeling_v1beta1.types.ListDataItemsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse): + 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 = data_labeling_service.ListDataItemsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.ListDataItemsResponse]: + 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[dataset.DataItem]: + for page in self.pages: + yield from page.data_items + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataItemsAsyncPager: + """A pager for iterating through ``list_data_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataItems`` requests and continue to iterate + through the ``data_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` + 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[data_labeling_service.ListDataItemsResponse]], + request: data_labeling_service.ListDataItemsRequest, + response: data_labeling_service.ListDataItemsResponse, + *, + 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.datalabeling_v1beta1.types.ListDataItemsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse): + 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 = data_labeling_service.ListDataItemsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.ListDataItemsResponse]: + 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[dataset.DataItem]: + async def async_generator(): + async for page in self.pages: + for response in page.data_items: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotatedDatasetsPager: + """A pager for iterating through ``list_annotated_datasets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``annotated_datasets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnnotatedDatasets`` requests and continue to iterate + through the ``annotated_datasets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` + 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[..., data_labeling_service.ListAnnotatedDatasetsResponse], + request: data_labeling_service.ListAnnotatedDatasetsRequest, + response: data_labeling_service.ListAnnotatedDatasetsResponse, + *, + 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.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse): + 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 = data_labeling_service.ListAnnotatedDatasetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.ListAnnotatedDatasetsResponse]: + 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[dataset.AnnotatedDataset]: + for page in self.pages: + yield from page.annotated_datasets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotatedDatasetsAsyncPager: + """A pager for iterating through ``list_annotated_datasets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``annotated_datasets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnnotatedDatasets`` requests and continue to iterate + through the ``annotated_datasets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` + 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[data_labeling_service.ListAnnotatedDatasetsResponse]], + request: data_labeling_service.ListAnnotatedDatasetsRequest, + response: data_labeling_service.ListAnnotatedDatasetsResponse, + *, + 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.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse): + 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 = data_labeling_service.ListAnnotatedDatasetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.ListAnnotatedDatasetsResponse]: + 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[dataset.AnnotatedDataset]: + async def async_generator(): + async for page in self.pages: + for response in page.annotated_datasets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExamplesPager: + """A pager for iterating through ``list_examples`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``examples`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExamples`` requests and continue to iterate + through the ``examples`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` + 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[..., data_labeling_service.ListExamplesResponse], + request: data_labeling_service.ListExamplesRequest, + response: data_labeling_service.ListExamplesResponse, + *, + 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.datalabeling_v1beta1.types.ListExamplesRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListExamplesResponse): + 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 = data_labeling_service.ListExamplesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.ListExamplesResponse]: + 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[dataset.Example]: + for page in self.pages: + yield from page.examples + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExamplesAsyncPager: + """A pager for iterating through ``list_examples`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``examples`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExamples`` requests and continue to iterate + through the ``examples`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` + 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[data_labeling_service.ListExamplesResponse]], + request: data_labeling_service.ListExamplesRequest, + response: data_labeling_service.ListExamplesResponse, + *, + 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.datalabeling_v1beta1.types.ListExamplesRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListExamplesResponse): + 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 = data_labeling_service.ListExamplesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.ListExamplesResponse]: + 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[dataset.Example]: + async def async_generator(): + async for page in self.pages: + for response in page.examples: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotationSpecSetsPager: + """A pager for iterating through ``list_annotation_spec_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``annotation_spec_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnnotationSpecSets`` requests and continue to iterate + through the ``annotation_spec_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` + 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[..., data_labeling_service.ListAnnotationSpecSetsResponse], + request: data_labeling_service.ListAnnotationSpecSetsRequest, + response: data_labeling_service.ListAnnotationSpecSetsResponse, + *, + 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.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse): + 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 = data_labeling_service.ListAnnotationSpecSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.ListAnnotationSpecSetsResponse]: + 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[annotation_spec_set.AnnotationSpecSet]: + for page in self.pages: + yield from page.annotation_spec_sets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotationSpecSetsAsyncPager: + """A pager for iterating through ``list_annotation_spec_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``annotation_spec_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnnotationSpecSets`` requests and continue to iterate + through the ``annotation_spec_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` + 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[data_labeling_service.ListAnnotationSpecSetsResponse]], + request: data_labeling_service.ListAnnotationSpecSetsRequest, + response: data_labeling_service.ListAnnotationSpecSetsResponse, + *, + 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.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse): + 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 = data_labeling_service.ListAnnotationSpecSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.ListAnnotationSpecSetsResponse]: + 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[annotation_spec_set.AnnotationSpecSet]: + async def async_generator(): + async for page in self.pages: + for response in page.annotation_spec_sets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstructionsPager: + """A pager for iterating through ``list_instructions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instructions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstructions`` requests and continue to iterate + through the ``instructions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` + 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[..., data_labeling_service.ListInstructionsResponse], + request: data_labeling_service.ListInstructionsRequest, + response: data_labeling_service.ListInstructionsResponse, + *, + 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.datalabeling_v1beta1.types.ListInstructionsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse): + 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 = data_labeling_service.ListInstructionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.ListInstructionsResponse]: + 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[instruction.Instruction]: + for page in self.pages: + yield from page.instructions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstructionsAsyncPager: + """A pager for iterating through ``list_instructions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instructions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstructions`` requests and continue to iterate + through the ``instructions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` + 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[data_labeling_service.ListInstructionsResponse]], + request: data_labeling_service.ListInstructionsRequest, + response: data_labeling_service.ListInstructionsResponse, + *, + 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.datalabeling_v1beta1.types.ListInstructionsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse): + 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 = data_labeling_service.ListInstructionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.ListInstructionsResponse]: + 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[instruction.Instruction]: + async def async_generator(): + async for page in self.pages: + for response in page.instructions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchEvaluationsPager: + """A pager for iterating through ``search_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` + 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[..., data_labeling_service.SearchEvaluationsResponse], + request: data_labeling_service.SearchEvaluationsRequest, + response: data_labeling_service.SearchEvaluationsResponse, + *, + 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.datalabeling_v1beta1.types.SearchEvaluationsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse): + 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 = data_labeling_service.SearchEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.SearchEvaluationsResponse]: + 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 SearchEvaluationsAsyncPager: + """A pager for iterating through ``search_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` + 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[data_labeling_service.SearchEvaluationsResponse]], + request: data_labeling_service.SearchEvaluationsRequest, + response: data_labeling_service.SearchEvaluationsResponse, + *, + 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.datalabeling_v1beta1.types.SearchEvaluationsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse): + 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 = data_labeling_service.SearchEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.SearchEvaluationsResponse]: + 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) + + +class SearchExampleComparisonsPager: + """A pager for iterating through ``search_example_comparisons`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``example_comparisons`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchExampleComparisons`` requests and continue to iterate + through the ``example_comparisons`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` + 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[..., data_labeling_service.SearchExampleComparisonsResponse], + request: data_labeling_service.SearchExampleComparisonsRequest, + response: data_labeling_service.SearchExampleComparisonsResponse, + *, + 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.datalabeling_v1beta1.types.SearchExampleComparisonsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse): + 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 = data_labeling_service.SearchExampleComparisonsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.SearchExampleComparisonsResponse]: + 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[data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison]: + for page in self.pages: + yield from page.example_comparisons + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchExampleComparisonsAsyncPager: + """A pager for iterating through ``search_example_comparisons`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``example_comparisons`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchExampleComparisons`` requests and continue to iterate + through the ``example_comparisons`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` + 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[data_labeling_service.SearchExampleComparisonsResponse]], + request: data_labeling_service.SearchExampleComparisonsRequest, + response: data_labeling_service.SearchExampleComparisonsResponse, + *, + 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.datalabeling_v1beta1.types.SearchExampleComparisonsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse): + 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 = data_labeling_service.SearchExampleComparisonsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.SearchExampleComparisonsResponse]: + 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[data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison]: + async def async_generator(): + async for page in self.pages: + for response in page.example_comparisons: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEvaluationJobsPager: + """A pager for iterating through ``list_evaluation_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluation_jobs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluationJobs`` requests and continue to iterate + through the ``evaluation_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` + 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[..., data_labeling_service.ListEvaluationJobsResponse], + request: data_labeling_service.ListEvaluationJobsRequest, + response: data_labeling_service.ListEvaluationJobsResponse, + *, + 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.datalabeling_v1beta1.types.ListEvaluationJobsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse): + 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 = data_labeling_service.ListEvaluationJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_labeling_service.ListEvaluationJobsResponse]: + 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_job.EvaluationJob]: + for page in self.pages: + yield from page.evaluation_jobs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEvaluationJobsAsyncPager: + """A pager for iterating through ``list_evaluation_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluation_jobs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluationJobs`` requests and continue to iterate + through the ``evaluation_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` + 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[data_labeling_service.ListEvaluationJobsResponse]], + request: data_labeling_service.ListEvaluationJobsRequest, + response: data_labeling_service.ListEvaluationJobsResponse, + *, + 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.datalabeling_v1beta1.types.ListEvaluationJobsRequest): + The initial request object. + response (google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse): + 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 = data_labeling_service.ListEvaluationJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_labeling_service.ListEvaluationJobsResponse]: + 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_job.EvaluationJob]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluation_jobs: + 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/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py new file mode 100644 index 0000000..52111f1 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 DataLabelingServiceTransport +from .grpc import DataLabelingServiceGrpcTransport +from .grpc_asyncio import DataLabelingServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataLabelingServiceTransport]] +_transport_registry['grpc'] = DataLabelingServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DataLabelingServiceGrpcAsyncIOTransport + +__all__ = ( + 'DataLabelingServiceTransport', + 'DataLabelingServiceGrpcTransport', + 'DataLabelingServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py new file mode 100644 index 0000000..88bf88a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py @@ -0,0 +1,802 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import data_labeling_service +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job +from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job +from google.cloud.datalabeling_v1beta1.types import instruction +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-datalabeling', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class DataLabelingServiceTransport(abc.ABC): + """Abstract transport class for DataLabelingService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'datalabeling.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, 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) + + # 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_dataset: gapic_v1.method.wrap_method( + self.create_dataset, + default_timeout=30.0, + client_info=client_info, + ), + self.get_dataset: gapic_v1.method.wrap_method( + self.get_dataset, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_datasets: gapic_v1.method.wrap_method( + self.list_datasets, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_dataset: gapic_v1.method.wrap_method( + self.delete_dataset, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_data: gapic_v1.method.wrap_method( + self.import_data, + default_timeout=30.0, + client_info=client_info, + ), + self.export_data: gapic_v1.method.wrap_method( + self.export_data, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_data_item: gapic_v1.method.wrap_method( + self.get_data_item, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_data_items: gapic_v1.method.wrap_method( + self.list_data_items, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_annotated_dataset: gapic_v1.method.wrap_method( + self.get_annotated_dataset, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_annotated_datasets: gapic_v1.method.wrap_method( + self.list_annotated_datasets, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_annotated_dataset: gapic_v1.method.wrap_method( + self.delete_annotated_dataset, + default_timeout=None, + client_info=client_info, + ), + self.label_image: gapic_v1.method.wrap_method( + self.label_image, + default_timeout=30.0, + client_info=client_info, + ), + self.label_video: gapic_v1.method.wrap_method( + self.label_video, + default_timeout=30.0, + client_info=client_info, + ), + self.label_text: gapic_v1.method.wrap_method( + self.label_text, + default_timeout=30.0, + client_info=client_info, + ), + self.get_example: gapic_v1.method.wrap_method( + self.get_example, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_examples: gapic_v1.method.wrap_method( + self.list_examples, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_annotation_spec_set: gapic_v1.method.wrap_method( + self.create_annotation_spec_set, + default_timeout=30.0, + client_info=client_info, + ), + self.get_annotation_spec_set: gapic_v1.method.wrap_method( + self.get_annotation_spec_set, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_annotation_spec_sets: gapic_v1.method.wrap_method( + self.list_annotation_spec_sets, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_annotation_spec_set: gapic_v1.method.wrap_method( + self.delete_annotation_spec_set, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_instruction: gapic_v1.method.wrap_method( + self.create_instruction, + default_timeout=30.0, + client_info=client_info, + ), + self.get_instruction: gapic_v1.method.wrap_method( + self.get_instruction, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_instructions: gapic_v1.method.wrap_method( + self.list_instructions, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_instruction: gapic_v1.method.wrap_method( + self.delete_instruction, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_evaluation: gapic_v1.method.wrap_method( + self.get_evaluation, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.search_evaluations: gapic_v1.method.wrap_method( + self.search_evaluations, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.search_example_comparisons: gapic_v1.method.wrap_method( + self.search_example_comparisons, + default_timeout=30.0, + client_info=client_info, + ), + self.create_evaluation_job: gapic_v1.method.wrap_method( + self.create_evaluation_job, + default_timeout=30.0, + client_info=client_info, + ), + self.update_evaluation_job: gapic_v1.method.wrap_method( + self.update_evaluation_job, + default_timeout=30.0, + client_info=client_info, + ), + self.get_evaluation_job: gapic_v1.method.wrap_method( + self.get_evaluation_job, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.pause_evaluation_job: gapic_v1.method.wrap_method( + self.pause_evaluation_job, + default_timeout=30.0, + client_info=client_info, + ), + self.resume_evaluation_job: gapic_v1.method.wrap_method( + self.resume_evaluation_job, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_evaluation_job: gapic_v1.method.wrap_method( + self.delete_evaluation_job, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_evaluation_jobs: gapic_v1.method.wrap_method( + self.list_evaluation_jobs, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.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) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_dataset(self) -> Callable[ + [data_labeling_service.CreateDatasetRequest], + Union[ + gcd_dataset.Dataset, + Awaitable[gcd_dataset.Dataset] + ]]: + raise NotImplementedError() + + @property + def get_dataset(self) -> Callable[ + [data_labeling_service.GetDatasetRequest], + Union[ + dataset.Dataset, + Awaitable[dataset.Dataset] + ]]: + raise NotImplementedError() + + @property + def list_datasets(self) -> Callable[ + [data_labeling_service.ListDatasetsRequest], + Union[ + data_labeling_service.ListDatasetsResponse, + Awaitable[data_labeling_service.ListDatasetsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_dataset(self) -> Callable[ + [data_labeling_service.DeleteDatasetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_data(self) -> Callable[ + [data_labeling_service.ImportDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_data(self) -> Callable[ + [data_labeling_service.ExportDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_data_item(self) -> Callable[ + [data_labeling_service.GetDataItemRequest], + Union[ + dataset.DataItem, + Awaitable[dataset.DataItem] + ]]: + raise NotImplementedError() + + @property + def list_data_items(self) -> Callable[ + [data_labeling_service.ListDataItemsRequest], + Union[ + data_labeling_service.ListDataItemsResponse, + Awaitable[data_labeling_service.ListDataItemsResponse] + ]]: + raise NotImplementedError() + + @property + def get_annotated_dataset(self) -> Callable[ + [data_labeling_service.GetAnnotatedDatasetRequest], + Union[ + dataset.AnnotatedDataset, + Awaitable[dataset.AnnotatedDataset] + ]]: + raise NotImplementedError() + + @property + def list_annotated_datasets(self) -> Callable[ + [data_labeling_service.ListAnnotatedDatasetsRequest], + Union[ + data_labeling_service.ListAnnotatedDatasetsResponse, + Awaitable[data_labeling_service.ListAnnotatedDatasetsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_annotated_dataset(self) -> Callable[ + [data_labeling_service.DeleteAnnotatedDatasetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def label_image(self) -> Callable[ + [data_labeling_service.LabelImageRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def label_video(self) -> Callable[ + [data_labeling_service.LabelVideoRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def label_text(self) -> Callable[ + [data_labeling_service.LabelTextRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_example(self) -> Callable[ + [data_labeling_service.GetExampleRequest], + Union[ + dataset.Example, + Awaitable[dataset.Example] + ]]: + raise NotImplementedError() + + @property + def list_examples(self) -> Callable[ + [data_labeling_service.ListExamplesRequest], + Union[ + data_labeling_service.ListExamplesResponse, + Awaitable[data_labeling_service.ListExamplesResponse] + ]]: + raise NotImplementedError() + + @property + def create_annotation_spec_set(self) -> Callable[ + [data_labeling_service.CreateAnnotationSpecSetRequest], + Union[ + gcd_annotation_spec_set.AnnotationSpecSet, + Awaitable[gcd_annotation_spec_set.AnnotationSpecSet] + ]]: + raise NotImplementedError() + + @property + def get_annotation_spec_set(self) -> Callable[ + [data_labeling_service.GetAnnotationSpecSetRequest], + Union[ + annotation_spec_set.AnnotationSpecSet, + Awaitable[annotation_spec_set.AnnotationSpecSet] + ]]: + raise NotImplementedError() + + @property + def list_annotation_spec_sets(self) -> Callable[ + [data_labeling_service.ListAnnotationSpecSetsRequest], + Union[ + data_labeling_service.ListAnnotationSpecSetsResponse, + Awaitable[data_labeling_service.ListAnnotationSpecSetsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_annotation_spec_set(self) -> Callable[ + [data_labeling_service.DeleteAnnotationSpecSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_instruction(self) -> Callable[ + [data_labeling_service.CreateInstructionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_instruction(self) -> Callable[ + [data_labeling_service.GetInstructionRequest], + Union[ + instruction.Instruction, + Awaitable[instruction.Instruction] + ]]: + raise NotImplementedError() + + @property + def list_instructions(self) -> Callable[ + [data_labeling_service.ListInstructionsRequest], + Union[ + data_labeling_service.ListInstructionsResponse, + Awaitable[data_labeling_service.ListInstructionsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_instruction(self) -> Callable[ + [data_labeling_service.DeleteInstructionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_evaluation(self) -> Callable[ + [data_labeling_service.GetEvaluationRequest], + Union[ + evaluation.Evaluation, + Awaitable[evaluation.Evaluation] + ]]: + raise NotImplementedError() + + @property + def search_evaluations(self) -> Callable[ + [data_labeling_service.SearchEvaluationsRequest], + Union[ + data_labeling_service.SearchEvaluationsResponse, + Awaitable[data_labeling_service.SearchEvaluationsResponse] + ]]: + raise NotImplementedError() + + @property + def search_example_comparisons(self) -> Callable[ + [data_labeling_service.SearchExampleComparisonsRequest], + Union[ + data_labeling_service.SearchExampleComparisonsResponse, + Awaitable[data_labeling_service.SearchExampleComparisonsResponse] + ]]: + raise NotImplementedError() + + @property + def create_evaluation_job(self) -> Callable[ + [data_labeling_service.CreateEvaluationJobRequest], + Union[ + evaluation_job.EvaluationJob, + Awaitable[evaluation_job.EvaluationJob] + ]]: + raise NotImplementedError() + + @property + def update_evaluation_job(self) -> Callable[ + [data_labeling_service.UpdateEvaluationJobRequest], + Union[ + gcd_evaluation_job.EvaluationJob, + Awaitable[gcd_evaluation_job.EvaluationJob] + ]]: + raise NotImplementedError() + + @property + def get_evaluation_job(self) -> Callable[ + [data_labeling_service.GetEvaluationJobRequest], + Union[ + evaluation_job.EvaluationJob, + Awaitable[evaluation_job.EvaluationJob] + ]]: + raise NotImplementedError() + + @property + def pause_evaluation_job(self) -> Callable[ + [data_labeling_service.PauseEvaluationJobRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def resume_evaluation_job(self) -> Callable[ + [data_labeling_service.ResumeEvaluationJobRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_evaluation_job(self) -> Callable[ + [data_labeling_service.DeleteEvaluationJobRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_evaluation_jobs(self) -> Callable[ + [data_labeling_service.ListEvaluationJobsRequest], + Union[ + data_labeling_service.ListEvaluationJobsResponse, + Awaitable[data_labeling_service.ListEvaluationJobsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DataLabelingServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py new file mode 100644 index 0000000..117308e --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py @@ -0,0 +1,1177 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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.datalabeling_v1beta1.types import annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import data_labeling_service +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job +from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job +from google.cloud.datalabeling_v1beta1.types import instruction +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO + + +class DataLabelingServiceGrpcTransport(DataLabelingServiceTransport): + """gRPC backend transport for DataLabelingService. + + Service for the AI Platform Data Labeling API. + + 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 = 'datalabeling.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 = 'datalabeling.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity 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 create_dataset(self) -> Callable[ + [data_labeling_service.CreateDatasetRequest], + gcd_dataset.Dataset]: + r"""Return a callable for the create dataset method over gRPC. + + Creates dataset. If success return a Dataset + resource. + + Returns: + Callable[[~.CreateDatasetRequest], + ~.Dataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['create_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateDataset', + request_serializer=data_labeling_service.CreateDatasetRequest.serialize, + response_deserializer=gcd_dataset.Dataset.deserialize, + ) + return self._stubs['create_dataset'] + + @property + def get_dataset(self) -> Callable[ + [data_labeling_service.GetDatasetRequest], + dataset.Dataset]: + r"""Return a callable for the get dataset method over gRPC. + + Gets dataset by resource name. + + Returns: + Callable[[~.GetDatasetRequest], + ~.Dataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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' not in self._stubs: + self._stubs['get_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataset', + request_serializer=data_labeling_service.GetDatasetRequest.serialize, + response_deserializer=dataset.Dataset.deserialize, + ) + return self._stubs['get_dataset'] + + @property + def list_datasets(self) -> Callable[ + [data_labeling_service.ListDatasetsRequest], + data_labeling_service.ListDatasetsResponse]: + r"""Return a callable for the list datasets method over gRPC. + + Lists datasets under a project. Pagination is + supported. + + Returns: + Callable[[~.ListDatasetsRequest], + ~.ListDatasetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_datasets' not in self._stubs: + self._stubs['list_datasets'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDatasets', + request_serializer=data_labeling_service.ListDatasetsRequest.serialize, + response_deserializer=data_labeling_service.ListDatasetsResponse.deserialize, + ) + return self._stubs['list_datasets'] + + @property + def delete_dataset(self) -> Callable[ + [data_labeling_service.DeleteDatasetRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete dataset method over gRPC. + + Deletes a dataset by resource name. + + Returns: + Callable[[~.DeleteDatasetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['delete_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteDataset', + request_serializer=data_labeling_service.DeleteDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_dataset'] + + @property + def import_data(self) -> Callable[ + [data_labeling_service.ImportDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import data method over gRPC. + + Imports data into dataset based on source locations + defined in request. It can be called multiple times for + the same dataset. Each dataset can only have one long + running operation running on it. For example, no + labeling task (also long running operation) can be + started while importing is still ongoing. Vice versa. + + Returns: + Callable[[~.ImportDataRequest], + ~.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_data' not in self._stubs: + self._stubs['import_data'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ImportData', + request_serializer=data_labeling_service.ImportDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_data'] + + @property + def export_data(self) -> Callable[ + [data_labeling_service.ExportDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the export data method over gRPC. + + Exports data and annotations from dataset. + + Returns: + Callable[[~.ExportDataRequest], + ~.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 'export_data' not in self._stubs: + self._stubs['export_data'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ExportData', + request_serializer=data_labeling_service.ExportDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_data'] + + @property + def get_data_item(self) -> Callable[ + [data_labeling_service.GetDataItemRequest], + dataset.DataItem]: + r"""Return a callable for the get data item method over gRPC. + + Gets a data item in a dataset by resource name. This + API can be called after data are imported into dataset. + + Returns: + Callable[[~.GetDataItemRequest], + ~.DataItem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_item' not in self._stubs: + self._stubs['get_data_item'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataItem', + request_serializer=data_labeling_service.GetDataItemRequest.serialize, + response_deserializer=dataset.DataItem.deserialize, + ) + return self._stubs['get_data_item'] + + @property + def list_data_items(self) -> Callable[ + [data_labeling_service.ListDataItemsRequest], + data_labeling_service.ListDataItemsResponse]: + r"""Return a callable for the list data items method over gRPC. + + Lists data items in a dataset. This API can be called + after data are imported into dataset. Pagination is + supported. + + Returns: + Callable[[~.ListDataItemsRequest], + ~.ListDataItemsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_items' not in self._stubs: + self._stubs['list_data_items'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDataItems', + request_serializer=data_labeling_service.ListDataItemsRequest.serialize, + response_deserializer=data_labeling_service.ListDataItemsResponse.deserialize, + ) + return self._stubs['list_data_items'] + + @property + def get_annotated_dataset(self) -> Callable[ + [data_labeling_service.GetAnnotatedDatasetRequest], + dataset.AnnotatedDataset]: + r"""Return a callable for the get annotated dataset method over gRPC. + + Gets an annotated dataset by resource name. + + Returns: + Callable[[~.GetAnnotatedDatasetRequest], + ~.AnnotatedDataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: + self._stubs['get_annotated_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotatedDataset', + request_serializer=data_labeling_service.GetAnnotatedDatasetRequest.serialize, + response_deserializer=dataset.AnnotatedDataset.deserialize, + ) + return self._stubs['get_annotated_dataset'] + + @property + def list_annotated_datasets(self) -> Callable[ + [data_labeling_service.ListAnnotatedDatasetsRequest], + data_labeling_service.ListAnnotatedDatasetsResponse]: + r"""Return a callable for the list annotated datasets method over gRPC. + + Lists annotated datasets for a dataset. Pagination is + supported. + + Returns: + Callable[[~.ListAnnotatedDatasetsRequest], + ~.ListAnnotatedDatasetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotated_datasets' not in self._stubs: + self._stubs['list_annotated_datasets'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotatedDatasets', + request_serializer=data_labeling_service.ListAnnotatedDatasetsRequest.serialize, + response_deserializer=data_labeling_service.ListAnnotatedDatasetsResponse.deserialize, + ) + return self._stubs['list_annotated_datasets'] + + @property + def delete_annotated_dataset(self) -> Callable[ + [data_labeling_service.DeleteAnnotatedDatasetRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete annotated dataset method over gRPC. + + Deletes an annotated dataset by resource name. + + Returns: + Callable[[~.DeleteAnnotatedDatasetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: + self._stubs['delete_annotated_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotatedDataset', + request_serializer=data_labeling_service.DeleteAnnotatedDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotated_dataset'] + + @property + def label_image(self) -> Callable[ + [data_labeling_service.LabelImageRequest], + operations_pb2.Operation]: + r"""Return a callable for the label image method over gRPC. + + Starts a labeling task for image. The type of image + labeling task is configured by feature in the request. + + Returns: + Callable[[~.LabelImageRequest], + ~.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 'label_image' not in self._stubs: + self._stubs['label_image'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelImage', + request_serializer=data_labeling_service.LabelImageRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['label_image'] + + @property + def label_video(self) -> Callable[ + [data_labeling_service.LabelVideoRequest], + operations_pb2.Operation]: + r"""Return a callable for the label video method over gRPC. + + Starts a labeling task for video. The type of video + labeling task is configured by feature in the request. + + Returns: + Callable[[~.LabelVideoRequest], + ~.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 'label_video' not in self._stubs: + self._stubs['label_video'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelVideo', + request_serializer=data_labeling_service.LabelVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['label_video'] + + @property + def label_text(self) -> Callable[ + [data_labeling_service.LabelTextRequest], + operations_pb2.Operation]: + r"""Return a callable for the label text method over gRPC. + + Starts a labeling task for text. The type of text + labeling task is configured by feature in the request. + + Returns: + Callable[[~.LabelTextRequest], + ~.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 'label_text' not in self._stubs: + self._stubs['label_text'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelText', + request_serializer=data_labeling_service.LabelTextRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['label_text'] + + @property + def get_example(self) -> Callable[ + [data_labeling_service.GetExampleRequest], + dataset.Example]: + r"""Return a callable for the get example method over gRPC. + + Gets an example by resource name, including both data + and annotation. + + Returns: + Callable[[~.GetExampleRequest], + ~.Example]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_example' not in self._stubs: + self._stubs['get_example'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetExample', + request_serializer=data_labeling_service.GetExampleRequest.serialize, + response_deserializer=dataset.Example.deserialize, + ) + return self._stubs['get_example'] + + @property + def list_examples(self) -> Callable[ + [data_labeling_service.ListExamplesRequest], + data_labeling_service.ListExamplesResponse]: + r"""Return a callable for the list examples method over gRPC. + + Lists examples in an annotated dataset. Pagination is + supported. + + Returns: + Callable[[~.ListExamplesRequest], + ~.ListExamplesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_examples' not in self._stubs: + self._stubs['list_examples'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListExamples', + request_serializer=data_labeling_service.ListExamplesRequest.serialize, + response_deserializer=data_labeling_service.ListExamplesResponse.deserialize, + ) + return self._stubs['list_examples'] + + @property + def create_annotation_spec_set(self) -> Callable[ + [data_labeling_service.CreateAnnotationSpecSetRequest], + gcd_annotation_spec_set.AnnotationSpecSet]: + r"""Return a callable for the create annotation spec set method over gRPC. + + Creates an annotation spec set by providing a set of + labels. + + Returns: + Callable[[~.CreateAnnotationSpecSetRequest], + ~.AnnotationSpecSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: + self._stubs['create_annotation_spec_set'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateAnnotationSpecSet', + request_serializer=data_labeling_service.CreateAnnotationSpecSetRequest.serialize, + response_deserializer=gcd_annotation_spec_set.AnnotationSpecSet.deserialize, + ) + return self._stubs['create_annotation_spec_set'] + + @property + def get_annotation_spec_set(self) -> Callable[ + [data_labeling_service.GetAnnotationSpecSetRequest], + annotation_spec_set.AnnotationSpecSet]: + r"""Return a callable for the get annotation spec set method over gRPC. + + Gets an annotation spec set by resource name. + + Returns: + Callable[[~.GetAnnotationSpecSetRequest], + ~.AnnotationSpecSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: + self._stubs['get_annotation_spec_set'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotationSpecSet', + request_serializer=data_labeling_service.GetAnnotationSpecSetRequest.serialize, + response_deserializer=annotation_spec_set.AnnotationSpecSet.deserialize, + ) + return self._stubs['get_annotation_spec_set'] + + @property + def list_annotation_spec_sets(self) -> Callable[ + [data_labeling_service.ListAnnotationSpecSetsRequest], + data_labeling_service.ListAnnotationSpecSetsResponse]: + r"""Return a callable for the list annotation spec sets method over gRPC. + + Lists annotation spec sets for a project. Pagination + is supported. + + Returns: + Callable[[~.ListAnnotationSpecSetsRequest], + ~.ListAnnotationSpecSetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_sets' not in self._stubs: + self._stubs['list_annotation_spec_sets'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotationSpecSets', + request_serializer=data_labeling_service.ListAnnotationSpecSetsRequest.serialize, + response_deserializer=data_labeling_service.ListAnnotationSpecSetsResponse.deserialize, + ) + return self._stubs['list_annotation_spec_sets'] + + @property + def delete_annotation_spec_set(self) -> Callable[ + [data_labeling_service.DeleteAnnotationSpecSetRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete annotation spec set method over gRPC. + + Deletes an annotation spec set by resource name. + + Returns: + Callable[[~.DeleteAnnotationSpecSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: + self._stubs['delete_annotation_spec_set'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotationSpecSet', + request_serializer=data_labeling_service.DeleteAnnotationSpecSetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotation_spec_set'] + + @property + def create_instruction(self) -> Callable[ + [data_labeling_service.CreateInstructionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create instruction method over gRPC. + + Creates an instruction for how data should be + labeled. + + Returns: + Callable[[~.CreateInstructionRequest], + ~.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 'create_instruction' not in self._stubs: + self._stubs['create_instruction'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateInstruction', + request_serializer=data_labeling_service.CreateInstructionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instruction'] + + @property + def get_instruction(self) -> Callable[ + [data_labeling_service.GetInstructionRequest], + instruction.Instruction]: + r"""Return a callable for the get instruction method over gRPC. + + Gets an instruction by resource name. + + Returns: + Callable[[~.GetInstructionRequest], + ~.Instruction]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instruction' not in self._stubs: + self._stubs['get_instruction'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetInstruction', + request_serializer=data_labeling_service.GetInstructionRequest.serialize, + response_deserializer=instruction.Instruction.deserialize, + ) + return self._stubs['get_instruction'] + + @property + def list_instructions(self) -> Callable[ + [data_labeling_service.ListInstructionsRequest], + data_labeling_service.ListInstructionsResponse]: + r"""Return a callable for the list instructions method over gRPC. + + Lists instructions for a project. Pagination is + supported. + + Returns: + Callable[[~.ListInstructionsRequest], + ~.ListInstructionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instructions' not in self._stubs: + self._stubs['list_instructions'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListInstructions', + request_serializer=data_labeling_service.ListInstructionsRequest.serialize, + response_deserializer=data_labeling_service.ListInstructionsResponse.deserialize, + ) + return self._stubs['list_instructions'] + + @property + def delete_instruction(self) -> Callable[ + [data_labeling_service.DeleteInstructionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete instruction method over gRPC. + + Deletes an instruction object by resource name. + + Returns: + Callable[[~.DeleteInstructionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instruction' not in self._stubs: + self._stubs['delete_instruction'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteInstruction', + request_serializer=data_labeling_service.DeleteInstructionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_instruction'] + + @property + def get_evaluation(self) -> Callable[ + [data_labeling_service.GetEvaluationRequest], + evaluation.Evaluation]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets an evaluation by resource name (to search, use + [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). + + 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.datalabeling.v1beta1.DataLabelingService/GetEvaluation', + request_serializer=data_labeling_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs['get_evaluation'] + + @property + def search_evaluations(self) -> Callable[ + [data_labeling_service.SearchEvaluationsRequest], + data_labeling_service.SearchEvaluationsResponse]: + r"""Return a callable for the search evaluations method over gRPC. + + Searches + [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] + within a project. + + Returns: + Callable[[~.SearchEvaluationsRequest], + ~.SearchEvaluationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_evaluations' not in self._stubs: + self._stubs['search_evaluations'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchEvaluations', + request_serializer=data_labeling_service.SearchEvaluationsRequest.serialize, + response_deserializer=data_labeling_service.SearchEvaluationsResponse.deserialize, + ) + return self._stubs['search_evaluations'] + + @property + def search_example_comparisons(self) -> Callable[ + [data_labeling_service.SearchExampleComparisonsRequest], + data_labeling_service.SearchExampleComparisonsResponse]: + r"""Return a callable for the search example comparisons method over gRPC. + + Searches example comparisons from an evaluation. The + return format is a list of example comparisons that show + ground truth and prediction(s) for a single input. + Search by providing an evaluation ID. + + Returns: + Callable[[~.SearchExampleComparisonsRequest], + ~.SearchExampleComparisonsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_example_comparisons' not in self._stubs: + self._stubs['search_example_comparisons'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchExampleComparisons', + request_serializer=data_labeling_service.SearchExampleComparisonsRequest.serialize, + response_deserializer=data_labeling_service.SearchExampleComparisonsResponse.deserialize, + ) + return self._stubs['search_example_comparisons'] + + @property + def create_evaluation_job(self) -> Callable[ + [data_labeling_service.CreateEvaluationJobRequest], + evaluation_job.EvaluationJob]: + r"""Return a callable for the create evaluation job method over gRPC. + + Creates an evaluation job. + + Returns: + Callable[[~.CreateEvaluationJobRequest], + ~.EvaluationJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: + self._stubs['create_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateEvaluationJob', + request_serializer=data_labeling_service.CreateEvaluationJobRequest.serialize, + response_deserializer=evaluation_job.EvaluationJob.deserialize, + ) + return self._stubs['create_evaluation_job'] + + @property + def update_evaluation_job(self) -> Callable[ + [data_labeling_service.UpdateEvaluationJobRequest], + gcd_evaluation_job.EvaluationJob]: + r"""Return a callable for the update evaluation job method over gRPC. + + Updates an evaluation job. You can only update certain fields of + the job's + [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: + ``humanAnnotationConfig.instruction``, ``exampleCount``, and + ``exampleSamplePercentage``. + + If you want to change any other aspect of the evaluation job, + you must delete the job and create a new one. + + Returns: + Callable[[~.UpdateEvaluationJobRequest], + ~.EvaluationJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: + self._stubs['update_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/UpdateEvaluationJob', + request_serializer=data_labeling_service.UpdateEvaluationJobRequest.serialize, + response_deserializer=gcd_evaluation_job.EvaluationJob.deserialize, + ) + return self._stubs['update_evaluation_job'] + + @property + def get_evaluation_job(self) -> Callable[ + [data_labeling_service.GetEvaluationJobRequest], + evaluation_job.EvaluationJob]: + r"""Return a callable for the get evaluation job method over gRPC. + + Gets an evaluation job by resource name. + + Returns: + Callable[[~.GetEvaluationJobRequest], + ~.EvaluationJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_job' not in self._stubs: + self._stubs['get_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetEvaluationJob', + request_serializer=data_labeling_service.GetEvaluationJobRequest.serialize, + response_deserializer=evaluation_job.EvaluationJob.deserialize, + ) + return self._stubs['get_evaluation_job'] + + @property + def pause_evaluation_job(self) -> Callable[ + [data_labeling_service.PauseEvaluationJobRequest], + empty_pb2.Empty]: + r"""Return a callable for the pause evaluation job method over gRPC. + + Pauses an evaluation job. Pausing an evaluation job that is + already in a ``PAUSED`` state is a no-op. + + Returns: + Callable[[~.PauseEvaluationJobRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'pause_evaluation_job' not in self._stubs: + self._stubs['pause_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/PauseEvaluationJob', + request_serializer=data_labeling_service.PauseEvaluationJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['pause_evaluation_job'] + + @property + def resume_evaluation_job(self) -> Callable[ + [data_labeling_service.ResumeEvaluationJobRequest], + empty_pb2.Empty]: + r"""Return a callable for the resume evaluation job method over gRPC. + + Resumes a paused evaluation job. A deleted evaluation + job can't be resumed. Resuming a running or scheduled + evaluation job is a no-op. + + Returns: + Callable[[~.ResumeEvaluationJobRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resume_evaluation_job' not in self._stubs: + self._stubs['resume_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ResumeEvaluationJob', + request_serializer=data_labeling_service.ResumeEvaluationJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['resume_evaluation_job'] + + @property + def delete_evaluation_job(self) -> Callable[ + [data_labeling_service.DeleteEvaluationJobRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete evaluation job method over gRPC. + + Stops and deletes an evaluation job. + + Returns: + Callable[[~.DeleteEvaluationJobRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: + self._stubs['delete_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteEvaluationJob', + request_serializer=data_labeling_service.DeleteEvaluationJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_evaluation_job'] + + @property + def list_evaluation_jobs(self) -> Callable[ + [data_labeling_service.ListEvaluationJobsRequest], + data_labeling_service.ListEvaluationJobsResponse]: + r"""Return a callable for the list evaluation jobs method over gRPC. + + Lists all evaluation jobs within a project with + possible filters. Pagination is supported. + + Returns: + Callable[[~.ListEvaluationJobsRequest], + ~.ListEvaluationJobsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_jobs' not in self._stubs: + self._stubs['list_evaluation_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListEvaluationJobs', + request_serializer=data_labeling_service.ListEvaluationJobsRequest.serialize, + response_deserializer=data_labeling_service.ListEvaluationJobsResponse.deserialize, + ) + return self._stubs['list_evaluation_jobs'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'DataLabelingServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..9dc51c3 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py @@ -0,0 +1,1182 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import data_labeling_service +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job +from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job +from google.cloud.datalabeling_v1beta1.types import instruction +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DataLabelingServiceGrpcTransport + + +class DataLabelingServiceGrpcAsyncIOTransport(DataLabelingServiceTransport): + """gRPC AsyncIO backend transport for DataLabelingService. + + Service for the AI Platform Data Labeling API. + + 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 = 'datalabeling.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'datalabeling.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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. + """ + # Sanity 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 create_dataset(self) -> Callable[ + [data_labeling_service.CreateDatasetRequest], + Awaitable[gcd_dataset.Dataset]]: + r"""Return a callable for the create dataset method over gRPC. + + Creates dataset. If success return a Dataset + resource. + + Returns: + Callable[[~.CreateDatasetRequest], + Awaitable[~.Dataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['create_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateDataset', + request_serializer=data_labeling_service.CreateDatasetRequest.serialize, + response_deserializer=gcd_dataset.Dataset.deserialize, + ) + return self._stubs['create_dataset'] + + @property + def get_dataset(self) -> Callable[ + [data_labeling_service.GetDatasetRequest], + Awaitable[dataset.Dataset]]: + r"""Return a callable for the get dataset method over gRPC. + + Gets dataset by resource name. + + Returns: + Callable[[~.GetDatasetRequest], + Awaitable[~.Dataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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' not in self._stubs: + self._stubs['get_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataset', + request_serializer=data_labeling_service.GetDatasetRequest.serialize, + response_deserializer=dataset.Dataset.deserialize, + ) + return self._stubs['get_dataset'] + + @property + def list_datasets(self) -> Callable[ + [data_labeling_service.ListDatasetsRequest], + Awaitable[data_labeling_service.ListDatasetsResponse]]: + r"""Return a callable for the list datasets method over gRPC. + + Lists datasets under a project. Pagination is + supported. + + Returns: + Callable[[~.ListDatasetsRequest], + Awaitable[~.ListDatasetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_datasets' not in self._stubs: + self._stubs['list_datasets'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDatasets', + request_serializer=data_labeling_service.ListDatasetsRequest.serialize, + response_deserializer=data_labeling_service.ListDatasetsResponse.deserialize, + ) + return self._stubs['list_datasets'] + + @property + def delete_dataset(self) -> Callable[ + [data_labeling_service.DeleteDatasetRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete dataset method over gRPC. + + Deletes a dataset by resource name. + + Returns: + Callable[[~.DeleteDatasetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['delete_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteDataset', + request_serializer=data_labeling_service.DeleteDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_dataset'] + + @property + def import_data(self) -> Callable[ + [data_labeling_service.ImportDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import data method over gRPC. + + Imports data into dataset based on source locations + defined in request. It can be called multiple times for + the same dataset. Each dataset can only have one long + running operation running on it. For example, no + labeling task (also long running operation) can be + started while importing is still ongoing. Vice versa. + + Returns: + Callable[[~.ImportDataRequest], + 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_data' not in self._stubs: + self._stubs['import_data'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ImportData', + request_serializer=data_labeling_service.ImportDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_data'] + + @property + def export_data(self) -> Callable[ + [data_labeling_service.ExportDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export data method over gRPC. + + Exports data and annotations from dataset. + + Returns: + Callable[[~.ExportDataRequest], + 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 'export_data' not in self._stubs: + self._stubs['export_data'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ExportData', + request_serializer=data_labeling_service.ExportDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_data'] + + @property + def get_data_item(self) -> Callable[ + [data_labeling_service.GetDataItemRequest], + Awaitable[dataset.DataItem]]: + r"""Return a callable for the get data item method over gRPC. + + Gets a data item in a dataset by resource name. This + API can be called after data are imported into dataset. + + Returns: + Callable[[~.GetDataItemRequest], + Awaitable[~.DataItem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_item' not in self._stubs: + self._stubs['get_data_item'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataItem', + request_serializer=data_labeling_service.GetDataItemRequest.serialize, + response_deserializer=dataset.DataItem.deserialize, + ) + return self._stubs['get_data_item'] + + @property + def list_data_items(self) -> Callable[ + [data_labeling_service.ListDataItemsRequest], + Awaitable[data_labeling_service.ListDataItemsResponse]]: + r"""Return a callable for the list data items method over gRPC. + + Lists data items in a dataset. This API can be called + after data are imported into dataset. Pagination is + supported. + + Returns: + Callable[[~.ListDataItemsRequest], + Awaitable[~.ListDataItemsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_items' not in self._stubs: + self._stubs['list_data_items'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDataItems', + request_serializer=data_labeling_service.ListDataItemsRequest.serialize, + response_deserializer=data_labeling_service.ListDataItemsResponse.deserialize, + ) + return self._stubs['list_data_items'] + + @property + def get_annotated_dataset(self) -> Callable[ + [data_labeling_service.GetAnnotatedDatasetRequest], + Awaitable[dataset.AnnotatedDataset]]: + r"""Return a callable for the get annotated dataset method over gRPC. + + Gets an annotated dataset by resource name. + + Returns: + Callable[[~.GetAnnotatedDatasetRequest], + Awaitable[~.AnnotatedDataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: + self._stubs['get_annotated_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotatedDataset', + request_serializer=data_labeling_service.GetAnnotatedDatasetRequest.serialize, + response_deserializer=dataset.AnnotatedDataset.deserialize, + ) + return self._stubs['get_annotated_dataset'] + + @property + def list_annotated_datasets(self) -> Callable[ + [data_labeling_service.ListAnnotatedDatasetsRequest], + Awaitable[data_labeling_service.ListAnnotatedDatasetsResponse]]: + r"""Return a callable for the list annotated datasets method over gRPC. + + Lists annotated datasets for a dataset. Pagination is + supported. + + Returns: + Callable[[~.ListAnnotatedDatasetsRequest], + Awaitable[~.ListAnnotatedDatasetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotated_datasets' not in self._stubs: + self._stubs['list_annotated_datasets'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotatedDatasets', + request_serializer=data_labeling_service.ListAnnotatedDatasetsRequest.serialize, + response_deserializer=data_labeling_service.ListAnnotatedDatasetsResponse.deserialize, + ) + return self._stubs['list_annotated_datasets'] + + @property + def delete_annotated_dataset(self) -> Callable[ + [data_labeling_service.DeleteAnnotatedDatasetRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete annotated dataset method over gRPC. + + Deletes an annotated dataset by resource name. + + Returns: + Callable[[~.DeleteAnnotatedDatasetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: + self._stubs['delete_annotated_dataset'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotatedDataset', + request_serializer=data_labeling_service.DeleteAnnotatedDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotated_dataset'] + + @property + def label_image(self) -> Callable[ + [data_labeling_service.LabelImageRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the label image method over gRPC. + + Starts a labeling task for image. The type of image + labeling task is configured by feature in the request. + + Returns: + Callable[[~.LabelImageRequest], + 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 'label_image' not in self._stubs: + self._stubs['label_image'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelImage', + request_serializer=data_labeling_service.LabelImageRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['label_image'] + + @property + def label_video(self) -> Callable[ + [data_labeling_service.LabelVideoRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the label video method over gRPC. + + Starts a labeling task for video. The type of video + labeling task is configured by feature in the request. + + Returns: + Callable[[~.LabelVideoRequest], + 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 'label_video' not in self._stubs: + self._stubs['label_video'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelVideo', + request_serializer=data_labeling_service.LabelVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['label_video'] + + @property + def label_text(self) -> Callable[ + [data_labeling_service.LabelTextRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the label text method over gRPC. + + Starts a labeling task for text. The type of text + labeling task is configured by feature in the request. + + Returns: + Callable[[~.LabelTextRequest], + 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 'label_text' not in self._stubs: + self._stubs['label_text'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelText', + request_serializer=data_labeling_service.LabelTextRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['label_text'] + + @property + def get_example(self) -> Callable[ + [data_labeling_service.GetExampleRequest], + Awaitable[dataset.Example]]: + r"""Return a callable for the get example method over gRPC. + + Gets an example by resource name, including both data + and annotation. + + Returns: + Callable[[~.GetExampleRequest], + Awaitable[~.Example]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_example' not in self._stubs: + self._stubs['get_example'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetExample', + request_serializer=data_labeling_service.GetExampleRequest.serialize, + response_deserializer=dataset.Example.deserialize, + ) + return self._stubs['get_example'] + + @property + def list_examples(self) -> Callable[ + [data_labeling_service.ListExamplesRequest], + Awaitable[data_labeling_service.ListExamplesResponse]]: + r"""Return a callable for the list examples method over gRPC. + + Lists examples in an annotated dataset. Pagination is + supported. + + Returns: + Callable[[~.ListExamplesRequest], + Awaitable[~.ListExamplesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_examples' not in self._stubs: + self._stubs['list_examples'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListExamples', + request_serializer=data_labeling_service.ListExamplesRequest.serialize, + response_deserializer=data_labeling_service.ListExamplesResponse.deserialize, + ) + return self._stubs['list_examples'] + + @property + def create_annotation_spec_set(self) -> Callable[ + [data_labeling_service.CreateAnnotationSpecSetRequest], + Awaitable[gcd_annotation_spec_set.AnnotationSpecSet]]: + r"""Return a callable for the create annotation spec set method over gRPC. + + Creates an annotation spec set by providing a set of + labels. + + Returns: + Callable[[~.CreateAnnotationSpecSetRequest], + Awaitable[~.AnnotationSpecSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: + self._stubs['create_annotation_spec_set'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateAnnotationSpecSet', + request_serializer=data_labeling_service.CreateAnnotationSpecSetRequest.serialize, + response_deserializer=gcd_annotation_spec_set.AnnotationSpecSet.deserialize, + ) + return self._stubs['create_annotation_spec_set'] + + @property + def get_annotation_spec_set(self) -> Callable[ + [data_labeling_service.GetAnnotationSpecSetRequest], + Awaitable[annotation_spec_set.AnnotationSpecSet]]: + r"""Return a callable for the get annotation spec set method over gRPC. + + Gets an annotation spec set by resource name. + + Returns: + Callable[[~.GetAnnotationSpecSetRequest], + Awaitable[~.AnnotationSpecSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: + self._stubs['get_annotation_spec_set'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotationSpecSet', + request_serializer=data_labeling_service.GetAnnotationSpecSetRequest.serialize, + response_deserializer=annotation_spec_set.AnnotationSpecSet.deserialize, + ) + return self._stubs['get_annotation_spec_set'] + + @property + def list_annotation_spec_sets(self) -> Callable[ + [data_labeling_service.ListAnnotationSpecSetsRequest], + Awaitable[data_labeling_service.ListAnnotationSpecSetsResponse]]: + r"""Return a callable for the list annotation spec sets method over gRPC. + + Lists annotation spec sets for a project. Pagination + is supported. + + Returns: + Callable[[~.ListAnnotationSpecSetsRequest], + Awaitable[~.ListAnnotationSpecSetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_sets' not in self._stubs: + self._stubs['list_annotation_spec_sets'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotationSpecSets', + request_serializer=data_labeling_service.ListAnnotationSpecSetsRequest.serialize, + response_deserializer=data_labeling_service.ListAnnotationSpecSetsResponse.deserialize, + ) + return self._stubs['list_annotation_spec_sets'] + + @property + def delete_annotation_spec_set(self) -> Callable[ + [data_labeling_service.DeleteAnnotationSpecSetRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete annotation spec set method over gRPC. + + Deletes an annotation spec set by resource name. + + Returns: + Callable[[~.DeleteAnnotationSpecSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: + self._stubs['delete_annotation_spec_set'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotationSpecSet', + request_serializer=data_labeling_service.DeleteAnnotationSpecSetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotation_spec_set'] + + @property + def create_instruction(self) -> Callable[ + [data_labeling_service.CreateInstructionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create instruction method over gRPC. + + Creates an instruction for how data should be + labeled. + + Returns: + Callable[[~.CreateInstructionRequest], + 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 'create_instruction' not in self._stubs: + self._stubs['create_instruction'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateInstruction', + request_serializer=data_labeling_service.CreateInstructionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instruction'] + + @property + def get_instruction(self) -> Callable[ + [data_labeling_service.GetInstructionRequest], + Awaitable[instruction.Instruction]]: + r"""Return a callable for the get instruction method over gRPC. + + Gets an instruction by resource name. + + Returns: + Callable[[~.GetInstructionRequest], + Awaitable[~.Instruction]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instruction' not in self._stubs: + self._stubs['get_instruction'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetInstruction', + request_serializer=data_labeling_service.GetInstructionRequest.serialize, + response_deserializer=instruction.Instruction.deserialize, + ) + return self._stubs['get_instruction'] + + @property + def list_instructions(self) -> Callable[ + [data_labeling_service.ListInstructionsRequest], + Awaitable[data_labeling_service.ListInstructionsResponse]]: + r"""Return a callable for the list instructions method over gRPC. + + Lists instructions for a project. Pagination is + supported. + + Returns: + Callable[[~.ListInstructionsRequest], + Awaitable[~.ListInstructionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instructions' not in self._stubs: + self._stubs['list_instructions'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListInstructions', + request_serializer=data_labeling_service.ListInstructionsRequest.serialize, + response_deserializer=data_labeling_service.ListInstructionsResponse.deserialize, + ) + return self._stubs['list_instructions'] + + @property + def delete_instruction(self) -> Callable[ + [data_labeling_service.DeleteInstructionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete instruction method over gRPC. + + Deletes an instruction object by resource name. + + Returns: + Callable[[~.DeleteInstructionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instruction' not in self._stubs: + self._stubs['delete_instruction'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteInstruction', + request_serializer=data_labeling_service.DeleteInstructionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_instruction'] + + @property + def get_evaluation(self) -> Callable[ + [data_labeling_service.GetEvaluationRequest], + Awaitable[evaluation.Evaluation]]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets an evaluation by resource name (to search, use + [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). + + 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.datalabeling.v1beta1.DataLabelingService/GetEvaluation', + request_serializer=data_labeling_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs['get_evaluation'] + + @property + def search_evaluations(self) -> Callable[ + [data_labeling_service.SearchEvaluationsRequest], + Awaitable[data_labeling_service.SearchEvaluationsResponse]]: + r"""Return a callable for the search evaluations method over gRPC. + + Searches + [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] + within a project. + + Returns: + Callable[[~.SearchEvaluationsRequest], + Awaitable[~.SearchEvaluationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_evaluations' not in self._stubs: + self._stubs['search_evaluations'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchEvaluations', + request_serializer=data_labeling_service.SearchEvaluationsRequest.serialize, + response_deserializer=data_labeling_service.SearchEvaluationsResponse.deserialize, + ) + return self._stubs['search_evaluations'] + + @property + def search_example_comparisons(self) -> Callable[ + [data_labeling_service.SearchExampleComparisonsRequest], + Awaitable[data_labeling_service.SearchExampleComparisonsResponse]]: + r"""Return a callable for the search example comparisons method over gRPC. + + Searches example comparisons from an evaluation. The + return format is a list of example comparisons that show + ground truth and prediction(s) for a single input. + Search by providing an evaluation ID. + + Returns: + Callable[[~.SearchExampleComparisonsRequest], + Awaitable[~.SearchExampleComparisonsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_example_comparisons' not in self._stubs: + self._stubs['search_example_comparisons'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchExampleComparisons', + request_serializer=data_labeling_service.SearchExampleComparisonsRequest.serialize, + response_deserializer=data_labeling_service.SearchExampleComparisonsResponse.deserialize, + ) + return self._stubs['search_example_comparisons'] + + @property + def create_evaluation_job(self) -> Callable[ + [data_labeling_service.CreateEvaluationJobRequest], + Awaitable[evaluation_job.EvaluationJob]]: + r"""Return a callable for the create evaluation job method over gRPC. + + Creates an evaluation job. + + Returns: + Callable[[~.CreateEvaluationJobRequest], + Awaitable[~.EvaluationJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: + self._stubs['create_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateEvaluationJob', + request_serializer=data_labeling_service.CreateEvaluationJobRequest.serialize, + response_deserializer=evaluation_job.EvaluationJob.deserialize, + ) + return self._stubs['create_evaluation_job'] + + @property + def update_evaluation_job(self) -> Callable[ + [data_labeling_service.UpdateEvaluationJobRequest], + Awaitable[gcd_evaluation_job.EvaluationJob]]: + r"""Return a callable for the update evaluation job method over gRPC. + + Updates an evaluation job. You can only update certain fields of + the job's + [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: + ``humanAnnotationConfig.instruction``, ``exampleCount``, and + ``exampleSamplePercentage``. + + If you want to change any other aspect of the evaluation job, + you must delete the job and create a new one. + + Returns: + Callable[[~.UpdateEvaluationJobRequest], + Awaitable[~.EvaluationJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: + self._stubs['update_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/UpdateEvaluationJob', + request_serializer=data_labeling_service.UpdateEvaluationJobRequest.serialize, + response_deserializer=gcd_evaluation_job.EvaluationJob.deserialize, + ) + return self._stubs['update_evaluation_job'] + + @property + def get_evaluation_job(self) -> Callable[ + [data_labeling_service.GetEvaluationJobRequest], + Awaitable[evaluation_job.EvaluationJob]]: + r"""Return a callable for the get evaluation job method over gRPC. + + Gets an evaluation job by resource name. + + Returns: + Callable[[~.GetEvaluationJobRequest], + Awaitable[~.EvaluationJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_job' not in self._stubs: + self._stubs['get_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetEvaluationJob', + request_serializer=data_labeling_service.GetEvaluationJobRequest.serialize, + response_deserializer=evaluation_job.EvaluationJob.deserialize, + ) + return self._stubs['get_evaluation_job'] + + @property + def pause_evaluation_job(self) -> Callable[ + [data_labeling_service.PauseEvaluationJobRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the pause evaluation job method over gRPC. + + Pauses an evaluation job. Pausing an evaluation job that is + already in a ``PAUSED`` state is a no-op. + + Returns: + Callable[[~.PauseEvaluationJobRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'pause_evaluation_job' not in self._stubs: + self._stubs['pause_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/PauseEvaluationJob', + request_serializer=data_labeling_service.PauseEvaluationJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['pause_evaluation_job'] + + @property + def resume_evaluation_job(self) -> Callable[ + [data_labeling_service.ResumeEvaluationJobRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the resume evaluation job method over gRPC. + + Resumes a paused evaluation job. A deleted evaluation + job can't be resumed. Resuming a running or scheduled + evaluation job is a no-op. + + Returns: + Callable[[~.ResumeEvaluationJobRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resume_evaluation_job' not in self._stubs: + self._stubs['resume_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ResumeEvaluationJob', + request_serializer=data_labeling_service.ResumeEvaluationJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['resume_evaluation_job'] + + @property + def delete_evaluation_job(self) -> Callable[ + [data_labeling_service.DeleteEvaluationJobRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete evaluation job method over gRPC. + + Stops and deletes an evaluation job. + + Returns: + Callable[[~.DeleteEvaluationJobRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: + self._stubs['delete_evaluation_job'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteEvaluationJob', + request_serializer=data_labeling_service.DeleteEvaluationJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_evaluation_job'] + + @property + def list_evaluation_jobs(self) -> Callable[ + [data_labeling_service.ListEvaluationJobsRequest], + Awaitable[data_labeling_service.ListEvaluationJobsResponse]]: + r"""Return a callable for the list evaluation jobs method over gRPC. + + Lists all evaluation jobs within a project with + possible filters. Pagination is supported. + + Returns: + Callable[[~.ListEvaluationJobsRequest], + Awaitable[~.ListEvaluationJobsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_jobs' not in self._stubs: + self._stubs['list_evaluation_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListEvaluationJobs', + request_serializer=data_labeling_service.ListEvaluationJobsRequest.serialize, + response_deserializer=data_labeling_service.ListEvaluationJobsResponse.deserialize, + ) + return self._stubs['list_evaluation_jobs'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DataLabelingServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py new file mode 100644 index 0000000..1baffe3 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py @@ -0,0 +1,308 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .annotation import ( + Annotation, + AnnotationMetadata, + AnnotationValue, + BoundingPoly, + ImageBoundingPolyAnnotation, + ImageClassificationAnnotation, + ImagePolylineAnnotation, + ImageSegmentationAnnotation, + NormalizedBoundingPoly, + NormalizedPolyline, + NormalizedVertex, + ObjectTrackingFrame, + OperatorMetadata, + Polyline, + SequentialSegment, + TextClassificationAnnotation, + TextEntityExtractionAnnotation, + TimeSegment, + Vertex, + VideoClassificationAnnotation, + VideoEventAnnotation, + VideoObjectTrackingAnnotation, + AnnotationSentiment, + AnnotationSource, + AnnotationType, +) +from .annotation_spec_set import ( + AnnotationSpec, + AnnotationSpecSet, +) +from .data_labeling_service import ( + CreateAnnotationSpecSetRequest, + CreateDatasetRequest, + CreateEvaluationJobRequest, + CreateInstructionRequest, + DeleteAnnotatedDatasetRequest, + DeleteAnnotationSpecSetRequest, + DeleteDatasetRequest, + DeleteEvaluationJobRequest, + DeleteInstructionRequest, + ExportDataRequest, + GetAnnotatedDatasetRequest, + GetAnnotationSpecSetRequest, + GetDataItemRequest, + GetDatasetRequest, + GetEvaluationJobRequest, + GetEvaluationRequest, + GetExampleRequest, + GetInstructionRequest, + ImportDataRequest, + LabelImageRequest, + LabelTextRequest, + LabelVideoRequest, + ListAnnotatedDatasetsRequest, + ListAnnotatedDatasetsResponse, + ListAnnotationSpecSetsRequest, + ListAnnotationSpecSetsResponse, + ListDataItemsRequest, + ListDataItemsResponse, + ListDatasetsRequest, + ListDatasetsResponse, + ListEvaluationJobsRequest, + ListEvaluationJobsResponse, + ListExamplesRequest, + ListExamplesResponse, + ListInstructionsRequest, + ListInstructionsResponse, + PauseEvaluationJobRequest, + ResumeEvaluationJobRequest, + SearchEvaluationsRequest, + SearchEvaluationsResponse, + SearchExampleComparisonsRequest, + SearchExampleComparisonsResponse, + UpdateEvaluationJobRequest, +) +from .data_payloads import ( + ImagePayload, + TextPayload, + VideoPayload, + VideoThumbnail, +) +from .dataset import ( + AnnotatedDataset, + AnnotatedDatasetMetadata, + BigQuerySource, + ClassificationMetadata, + DataItem, + Dataset, + Example, + GcsDestination, + GcsFolderDestination, + GcsSource, + InputConfig, + LabelStats, + OutputConfig, + TextMetadata, + DataType, +) +from .evaluation import ( + BoundingBoxEvaluationOptions, + ClassificationMetrics, + ConfusionMatrix, + Evaluation, + EvaluationConfig, + EvaluationMetrics, + ObjectDetectionMetrics, + PrCurve, +) +from .evaluation_job import ( + Attempt, + EvaluationJob, + EvaluationJobAlertConfig, + EvaluationJobConfig, +) +from .human_annotation_config import ( + BoundingPolyConfig, + EventConfig, + HumanAnnotationConfig, + ImageClassificationConfig, + ObjectDetectionConfig, + ObjectTrackingConfig, + PolylineConfig, + SegmentationConfig, + SentimentConfig, + TextClassificationConfig, + TextEntityExtractionConfig, + VideoClassificationConfig, + StringAggregationType, +) +from .instruction import ( + CsvInstruction, + Instruction, + PdfInstruction, +) +from .operations import ( + CreateInstructionMetadata, + ExportDataOperationMetadata, + ExportDataOperationResponse, + ImportDataOperationMetadata, + ImportDataOperationResponse, + LabelImageBoundingBoxOperationMetadata, + LabelImageBoundingPolyOperationMetadata, + LabelImageClassificationOperationMetadata, + LabelImageOrientedBoundingBoxOperationMetadata, + LabelImagePolylineOperationMetadata, + LabelImageSegmentationOperationMetadata, + LabelOperationMetadata, + LabelTextClassificationOperationMetadata, + LabelTextEntityExtractionOperationMetadata, + LabelVideoClassificationOperationMetadata, + LabelVideoEventOperationMetadata, + LabelVideoObjectDetectionOperationMetadata, + LabelVideoObjectTrackingOperationMetadata, +) + +__all__ = ( + 'Annotation', + 'AnnotationMetadata', + 'AnnotationValue', + 'BoundingPoly', + 'ImageBoundingPolyAnnotation', + 'ImageClassificationAnnotation', + 'ImagePolylineAnnotation', + 'ImageSegmentationAnnotation', + 'NormalizedBoundingPoly', + 'NormalizedPolyline', + 'NormalizedVertex', + 'ObjectTrackingFrame', + 'OperatorMetadata', + 'Polyline', + 'SequentialSegment', + 'TextClassificationAnnotation', + 'TextEntityExtractionAnnotation', + 'TimeSegment', + 'Vertex', + 'VideoClassificationAnnotation', + 'VideoEventAnnotation', + 'VideoObjectTrackingAnnotation', + 'AnnotationSentiment', + 'AnnotationSource', + 'AnnotationType', + 'AnnotationSpec', + 'AnnotationSpecSet', + 'CreateAnnotationSpecSetRequest', + 'CreateDatasetRequest', + 'CreateEvaluationJobRequest', + 'CreateInstructionRequest', + 'DeleteAnnotatedDatasetRequest', + 'DeleteAnnotationSpecSetRequest', + 'DeleteDatasetRequest', + 'DeleteEvaluationJobRequest', + 'DeleteInstructionRequest', + 'ExportDataRequest', + 'GetAnnotatedDatasetRequest', + 'GetAnnotationSpecSetRequest', + 'GetDataItemRequest', + 'GetDatasetRequest', + 'GetEvaluationJobRequest', + 'GetEvaluationRequest', + 'GetExampleRequest', + 'GetInstructionRequest', + 'ImportDataRequest', + 'LabelImageRequest', + 'LabelTextRequest', + 'LabelVideoRequest', + 'ListAnnotatedDatasetsRequest', + 'ListAnnotatedDatasetsResponse', + 'ListAnnotationSpecSetsRequest', + 'ListAnnotationSpecSetsResponse', + 'ListDataItemsRequest', + 'ListDataItemsResponse', + 'ListDatasetsRequest', + 'ListDatasetsResponse', + 'ListEvaluationJobsRequest', + 'ListEvaluationJobsResponse', + 'ListExamplesRequest', + 'ListExamplesResponse', + 'ListInstructionsRequest', + 'ListInstructionsResponse', + 'PauseEvaluationJobRequest', + 'ResumeEvaluationJobRequest', + 'SearchEvaluationsRequest', + 'SearchEvaluationsResponse', + 'SearchExampleComparisonsRequest', + 'SearchExampleComparisonsResponse', + 'UpdateEvaluationJobRequest', + 'ImagePayload', + 'TextPayload', + 'VideoPayload', + 'VideoThumbnail', + 'AnnotatedDataset', + 'AnnotatedDatasetMetadata', + 'BigQuerySource', + 'ClassificationMetadata', + 'DataItem', + 'Dataset', + 'Example', + 'GcsDestination', + 'GcsFolderDestination', + 'GcsSource', + 'InputConfig', + 'LabelStats', + 'OutputConfig', + 'TextMetadata', + 'DataType', + 'BoundingBoxEvaluationOptions', + 'ClassificationMetrics', + 'ConfusionMatrix', + 'Evaluation', + 'EvaluationConfig', + 'EvaluationMetrics', + 'ObjectDetectionMetrics', + 'PrCurve', + 'Attempt', + 'EvaluationJob', + 'EvaluationJobAlertConfig', + 'EvaluationJobConfig', + 'BoundingPolyConfig', + 'EventConfig', + 'HumanAnnotationConfig', + 'ImageClassificationConfig', + 'ObjectDetectionConfig', + 'ObjectTrackingConfig', + 'PolylineConfig', + 'SegmentationConfig', + 'SentimentConfig', + 'TextClassificationConfig', + 'TextEntityExtractionConfig', + 'VideoClassificationConfig', + 'StringAggregationType', + 'CsvInstruction', + 'Instruction', + 'PdfInstruction', + 'CreateInstructionMetadata', + 'ExportDataOperationMetadata', + 'ExportDataOperationResponse', + 'ImportDataOperationMetadata', + 'ImportDataOperationResponse', + 'LabelImageBoundingBoxOperationMetadata', + 'LabelImageBoundingPolyOperationMetadata', + 'LabelImageClassificationOperationMetadata', + 'LabelImageOrientedBoundingBoxOperationMetadata', + 'LabelImagePolylineOperationMetadata', + 'LabelImageSegmentationOperationMetadata', + 'LabelOperationMetadata', + 'LabelTextClassificationOperationMetadata', + 'LabelTextEntityExtractionOperationMetadata', + 'LabelVideoClassificationOperationMetadata', + 'LabelVideoEventOperationMetadata', + 'LabelVideoObjectDetectionOperationMetadata', + 'LabelVideoObjectTrackingOperationMetadata', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py new file mode 100644 index 0000000..1b3a8a5 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py @@ -0,0 +1,688 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'AnnotationSource', + 'AnnotationSentiment', + 'AnnotationType', + 'Annotation', + 'AnnotationValue', + 'ImageClassificationAnnotation', + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + 'NormalizedBoundingPoly', + 'ImageBoundingPolyAnnotation', + 'Polyline', + 'NormalizedPolyline', + 'ImagePolylineAnnotation', + 'ImageSegmentationAnnotation', + 'TextClassificationAnnotation', + 'TextEntityExtractionAnnotation', + 'SequentialSegment', + 'TimeSegment', + 'VideoClassificationAnnotation', + 'ObjectTrackingFrame', + 'VideoObjectTrackingAnnotation', + 'VideoEventAnnotation', + 'AnnotationMetadata', + 'OperatorMetadata', + }, +) + + +class AnnotationSource(proto.Enum): + r"""Specifies where the annotation comes from (whether it was + provided by a human labeler or a different source). + """ + ANNOTATION_SOURCE_UNSPECIFIED = 0 + OPERATOR = 3 + + +class AnnotationSentiment(proto.Enum): + r"""""" + ANNOTATION_SENTIMENT_UNSPECIFIED = 0 + NEGATIVE = 1 + POSITIVE = 2 + + +class AnnotationType(proto.Enum): + r"""""" + ANNOTATION_TYPE_UNSPECIFIED = 0 + IMAGE_CLASSIFICATION_ANNOTATION = 1 + IMAGE_BOUNDING_BOX_ANNOTATION = 2 + IMAGE_ORIENTED_BOUNDING_BOX_ANNOTATION = 13 + IMAGE_BOUNDING_POLY_ANNOTATION = 10 + IMAGE_POLYLINE_ANNOTATION = 11 + IMAGE_SEGMENTATION_ANNOTATION = 12 + VIDEO_SHOTS_CLASSIFICATION_ANNOTATION = 3 + VIDEO_OBJECT_TRACKING_ANNOTATION = 4 + VIDEO_OBJECT_DETECTION_ANNOTATION = 5 + VIDEO_EVENT_ANNOTATION = 6 + TEXT_CLASSIFICATION_ANNOTATION = 8 + TEXT_ENTITY_EXTRACTION_ANNOTATION = 9 + GENERAL_CLASSIFICATION_ANNOTATION = 14 + + +class Annotation(proto.Message): + r"""Annotation for Example. Each example may have one or more + annotations. For example in image classification problem, each + image might have one or more labels. We call labels binded with + this image an Annotation. + + Attributes: + name (str): + Output only. Unique name of this annotation, format is: + + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/{annotated_dataset}/examples/{example_id}/annotations/{annotation_id} + annotation_source (google.cloud.datalabeling_v1beta1.types.AnnotationSource): + Output only. The source of the annotation. + annotation_value (google.cloud.datalabeling_v1beta1.types.AnnotationValue): + Output only. This is the actual annotation + value, e.g classification, bounding box values + are stored here. + annotation_metadata (google.cloud.datalabeling_v1beta1.types.AnnotationMetadata): + Output only. Annotation metadata, including + information like votes for labels. + annotation_sentiment (google.cloud.datalabeling_v1beta1.types.AnnotationSentiment): + Output only. Sentiment for this annotation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + annotation_source = proto.Field( + proto.ENUM, + number=2, + enum='AnnotationSource', + ) + annotation_value = proto.Field( + proto.MESSAGE, + number=3, + message='AnnotationValue', + ) + annotation_metadata = proto.Field( + proto.MESSAGE, + number=4, + message='AnnotationMetadata', + ) + annotation_sentiment = proto.Field( + proto.ENUM, + number=6, + enum='AnnotationSentiment', + ) + + +class AnnotationValue(proto.Message): + r"""Annotation value for an example. + + Attributes: + image_classification_annotation (google.cloud.datalabeling_v1beta1.types.ImageClassificationAnnotation): + Annotation value for image classification + case. + image_bounding_poly_annotation (google.cloud.datalabeling_v1beta1.types.ImageBoundingPolyAnnotation): + Annotation value for image bounding box, + oriented bounding box and polygon cases. + image_polyline_annotation (google.cloud.datalabeling_v1beta1.types.ImagePolylineAnnotation): + Annotation value for image polyline cases. + Polyline here is different from BoundingPoly. It + is formed by line segments connected to each + other but not closed form(Bounding Poly). The + line segments can cross each other. + image_segmentation_annotation (google.cloud.datalabeling_v1beta1.types.ImageSegmentationAnnotation): + Annotation value for image segmentation. + text_classification_annotation (google.cloud.datalabeling_v1beta1.types.TextClassificationAnnotation): + Annotation value for text classification + case. + text_entity_extraction_annotation (google.cloud.datalabeling_v1beta1.types.TextEntityExtractionAnnotation): + Annotation value for text entity extraction + case. + video_classification_annotation (google.cloud.datalabeling_v1beta1.types.VideoClassificationAnnotation): + Annotation value for video classification + case. + video_object_tracking_annotation (google.cloud.datalabeling_v1beta1.types.VideoObjectTrackingAnnotation): + Annotation value for video object detection + and tracking case. + video_event_annotation (google.cloud.datalabeling_v1beta1.types.VideoEventAnnotation): + Annotation value for video event case. + """ + + image_classification_annotation = proto.Field( + proto.MESSAGE, + number=1, + oneof='value_type', + message='ImageClassificationAnnotation', + ) + image_bounding_poly_annotation = proto.Field( + proto.MESSAGE, + number=2, + oneof='value_type', + message='ImageBoundingPolyAnnotation', + ) + image_polyline_annotation = proto.Field( + proto.MESSAGE, + number=8, + oneof='value_type', + message='ImagePolylineAnnotation', + ) + image_segmentation_annotation = proto.Field( + proto.MESSAGE, + number=9, + oneof='value_type', + message='ImageSegmentationAnnotation', + ) + text_classification_annotation = proto.Field( + proto.MESSAGE, + number=3, + oneof='value_type', + message='TextClassificationAnnotation', + ) + text_entity_extraction_annotation = proto.Field( + proto.MESSAGE, + number=10, + oneof='value_type', + message='TextEntityExtractionAnnotation', + ) + video_classification_annotation = proto.Field( + proto.MESSAGE, + number=4, + oneof='value_type', + message='VideoClassificationAnnotation', + ) + video_object_tracking_annotation = proto.Field( + proto.MESSAGE, + number=5, + oneof='value_type', + message='VideoObjectTrackingAnnotation', + ) + video_event_annotation = proto.Field( + proto.MESSAGE, + number=6, + oneof='value_type', + message='VideoEventAnnotation', + ) + + +class ImageClassificationAnnotation(proto.Message): + r"""Image classification annotation definition. + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of image. + """ + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate. + """ + + x = proto.Field( + proto.INT32, + number=1, + ) + y = proto.Field( + proto.INT32, + number=2, + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field( + proto.FLOAT, + number=1, + ) + y = proto.Field( + proto.FLOAT, + number=2, + ) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon in the image. + + Attributes: + vertices (Sequence[google.cloud.datalabeling_v1beta1.types.Vertex]): + The bounding polygon vertices. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + + +class NormalizedBoundingPoly(proto.Message): + r"""Normalized bounding polygon. + + Attributes: + normalized_vertices (Sequence[google.cloud.datalabeling_v1beta1.types.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + normalized_vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class ImageBoundingPolyAnnotation(proto.Message): + r"""Image bounding poly annotation. It represents a polygon + including bounding box in the image. + + Attributes: + bounding_poly (google.cloud.datalabeling_v1beta1.types.BoundingPoly): + + normalized_bounding_poly (google.cloud.datalabeling_v1beta1.types.NormalizedBoundingPoly): + + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of object in this bounding polygon. + """ + + bounding_poly = proto.Field( + proto.MESSAGE, + number=2, + oneof='bounded_area', + message='BoundingPoly', + ) + normalized_bounding_poly = proto.Field( + proto.MESSAGE, + number=3, + oneof='bounded_area', + message='NormalizedBoundingPoly', + ) + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + + +class Polyline(proto.Message): + r"""A line with multiple line segments. + + Attributes: + vertices (Sequence[google.cloud.datalabeling_v1beta1.types.Vertex]): + The polyline vertices. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Vertex', + ) + + +class NormalizedPolyline(proto.Message): + r"""Normalized polyline. + + Attributes: + normalized_vertices (Sequence[google.cloud.datalabeling_v1beta1.types.NormalizedVertex]): + The normalized polyline vertices. + """ + + normalized_vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class ImagePolylineAnnotation(proto.Message): + r"""A polyline for the image annotation. + + Attributes: + polyline (google.cloud.datalabeling_v1beta1.types.Polyline): + + normalized_polyline (google.cloud.datalabeling_v1beta1.types.NormalizedPolyline): + + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of this polyline. + """ + + polyline = proto.Field( + proto.MESSAGE, + number=2, + oneof='poly', + message='Polyline', + ) + normalized_polyline = proto.Field( + proto.MESSAGE, + number=3, + oneof='poly', + message='NormalizedPolyline', + ) + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + + +class ImageSegmentationAnnotation(proto.Message): + r"""Image segmentation annotation. + + Attributes: + annotation_colors (Sequence[google.cloud.datalabeling_v1beta1.types.ImageSegmentationAnnotation.AnnotationColorsEntry]): + The mapping between rgb color and annotation + spec. The key is the rgb color represented in + format of rgb(0, 0, 0). The value is the + AnnotationSpec. + mime_type (str): + Image format. + image_bytes (bytes): + A byte string of a full image's color map. + """ + + annotation_colors = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + mime_type = proto.Field( + proto.STRING, + number=2, + ) + image_bytes = proto.Field( + proto.BYTES, + number=3, + ) + + +class TextClassificationAnnotation(proto.Message): + r"""Text classification annotation. + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of the text. + """ + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + + +class TextEntityExtractionAnnotation(proto.Message): + r"""Text entity extraction annotation. + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of the text entities. + sequential_segment (google.cloud.datalabeling_v1beta1.types.SequentialSegment): + Position of the entity. + """ + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + sequential_segment = proto.Field( + proto.MESSAGE, + number=2, + message='SequentialSegment', + ) + + +class SequentialSegment(proto.Message): + r"""Start and end position in a sequence (e.g. text segment). + + Attributes: + start (int): + Start position (inclusive). + end (int): + End position (exclusive). + """ + + start = proto.Field( + proto.INT32, + number=1, + ) + end = proto.Field( + proto.INT32, + number=2, + ) + + +class TimeSegment(proto.Message): + r"""A time period inside of an example that has a time dimension + (e.g. video). + + Attributes: + start_time_offset (google.protobuf.duration_pb2.Duration): + Start of the time segment (inclusive), + represented as the duration since the example + start. + end_time_offset (google.protobuf.duration_pb2.Duration): + End of the time segment (exclusive), + represented as the duration since the example + start. + """ + + start_time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class VideoClassificationAnnotation(proto.Message): + r"""Video classification annotation. + + Attributes: + time_segment (google.cloud.datalabeling_v1beta1.types.TimeSegment): + The time segment of the video to which the + annotation applies. + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of the segment specified by time_segment. + """ + + time_segment = proto.Field( + proto.MESSAGE, + number=1, + message='TimeSegment', + ) + annotation_spec = proto.Field( + proto.MESSAGE, + number=2, + message=annotation_spec_set.AnnotationSpec, + ) + + +class ObjectTrackingFrame(proto.Message): + r"""Video frame level annotation for object detection and + tracking. + + Attributes: + bounding_poly (google.cloud.datalabeling_v1beta1.types.BoundingPoly): + + normalized_bounding_poly (google.cloud.datalabeling_v1beta1.types.NormalizedBoundingPoly): + + time_offset (google.protobuf.duration_pb2.Duration): + The time offset of this frame relative to the + beginning of the video. + """ + + bounding_poly = proto.Field( + proto.MESSAGE, + number=1, + oneof='bounded_area', + message='BoundingPoly', + ) + normalized_bounding_poly = proto.Field( + proto.MESSAGE, + number=2, + oneof='bounded_area', + message='NormalizedBoundingPoly', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + +class VideoObjectTrackingAnnotation(proto.Message): + r"""Video object tracking annotation. + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of the object tracked in this + annotation. + time_segment (google.cloud.datalabeling_v1beta1.types.TimeSegment): + The time segment of the video to which object + tracking applies. + object_tracking_frames (Sequence[google.cloud.datalabeling_v1beta1.types.ObjectTrackingFrame]): + The list of frames where this object track + appears. + """ + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + time_segment = proto.Field( + proto.MESSAGE, + number=2, + message='TimeSegment', + ) + object_tracking_frames = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ObjectTrackingFrame', + ) + + +class VideoEventAnnotation(proto.Message): + r"""Video event annotation. + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + Label of the event in this annotation. + time_segment (google.cloud.datalabeling_v1beta1.types.TimeSegment): + The time segment of the video to which the + annotation applies. + """ + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + time_segment = proto.Field( + proto.MESSAGE, + number=2, + message='TimeSegment', + ) + + +class AnnotationMetadata(proto.Message): + r"""Additional information associated with the annotation. + + Attributes: + operator_metadata (google.cloud.datalabeling_v1beta1.types.OperatorMetadata): + Metadata related to human labeling. + """ + + operator_metadata = proto.Field( + proto.MESSAGE, + number=2, + message='OperatorMetadata', + ) + + +class OperatorMetadata(proto.Message): + r"""General information useful for labels coming from + contributors. + + Attributes: + score (float): + Confidence score corresponding to a label. + For examle, if 3 contributors have answered the + question and 2 of them agree on the final label, + the confidence score will be 0.67 (2/3). + total_votes (int): + The total number of contributors that answer + this question. + label_votes (int): + The total number of contributors that choose + this label. + comments (Sequence[str]): + Comments from contributors. + """ + + score = proto.Field( + proto.FLOAT, + number=1, + ) + total_votes = proto.Field( + proto.INT32, + number=2, + ) + label_votes = proto.Field( + proto.INT32, + number=3, + ) + comments = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py new file mode 100644 index 0000000..bd887bc --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py @@ -0,0 +1,108 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'AnnotationSpecSet', + 'AnnotationSpec', + }, +) + + +class AnnotationSpecSet(proto.Message): + r"""An AnnotationSpecSet is a collection of label definitions. + For example, in image classification tasks, you define a set of + possible labels for images as an AnnotationSpecSet. An + AnnotationSpecSet is immutable upon creation. + + Attributes: + name (str): + Output only. The AnnotationSpecSet resource name in the + following format: + + "projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}". + display_name (str): + Required. The display name for + AnnotationSpecSet that you define when you + create it. Maximum of 64 characters. + description (str): + Optional. User-provided description of the + annotation specification set. The description + can be up to 10,000 characters long. + annotation_specs (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotationSpec]): + Required. The array of AnnotationSpecs that + you define when you create the + AnnotationSpecSet. These are the possible labels + for the labeling task. + blocking_resources (Sequence[str]): + Output only. The names of any related + resources that are blocking changes to the + annotation spec set. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + annotation_specs = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AnnotationSpec', + ) + blocking_resources = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class AnnotationSpec(proto.Message): + r"""Container of information related to one possible annotation that can + be used in a labeling task. For example, an image classification + task where images are labeled as ``dog`` or ``cat`` must reference + an AnnotationSpec for ``dog`` and an AnnotationSpec for ``cat``. + + Attributes: + display_name (str): + Required. The display name of the + AnnotationSpec. Maximum of 64 characters. + description (str): + Optional. User-provided description of the + annotation specification. The description can be + up to 10,000 characters long. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py new file mode 100644 index 0000000..e22ec3c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py @@ -0,0 +1,1375 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job +from google.cloud.datalabeling_v1beta1.types import human_annotation_config +from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'CreateDatasetRequest', + 'GetDatasetRequest', + 'ListDatasetsRequest', + 'ListDatasetsResponse', + 'DeleteDatasetRequest', + 'ImportDataRequest', + 'ExportDataRequest', + 'GetDataItemRequest', + 'ListDataItemsRequest', + 'ListDataItemsResponse', + 'GetAnnotatedDatasetRequest', + 'ListAnnotatedDatasetsRequest', + 'ListAnnotatedDatasetsResponse', + 'DeleteAnnotatedDatasetRequest', + 'LabelImageRequest', + 'LabelVideoRequest', + 'LabelTextRequest', + 'GetExampleRequest', + 'ListExamplesRequest', + 'ListExamplesResponse', + 'CreateAnnotationSpecSetRequest', + 'GetAnnotationSpecSetRequest', + 'ListAnnotationSpecSetsRequest', + 'ListAnnotationSpecSetsResponse', + 'DeleteAnnotationSpecSetRequest', + 'CreateInstructionRequest', + 'GetInstructionRequest', + 'DeleteInstructionRequest', + 'ListInstructionsRequest', + 'ListInstructionsResponse', + 'GetEvaluationRequest', + 'SearchEvaluationsRequest', + 'SearchEvaluationsResponse', + 'SearchExampleComparisonsRequest', + 'SearchExampleComparisonsResponse', + 'CreateEvaluationJobRequest', + 'UpdateEvaluationJobRequest', + 'GetEvaluationJobRequest', + 'PauseEvaluationJobRequest', + 'ResumeEvaluationJobRequest', + 'DeleteEvaluationJobRequest', + 'ListEvaluationJobsRequest', + 'ListEvaluationJobsResponse', + }, +) + + +class CreateDatasetRequest(proto.Message): + r"""Request message for CreateDataset. + + Attributes: + parent (str): + Required. Dataset resource parent, format: + projects/{project_id} + dataset (google.cloud.datalabeling_v1beta1.types.Dataset): + Required. The dataset to be created. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + dataset = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_dataset.Dataset, + ) + + +class GetDatasetRequest(proto.Message): + r"""Request message for GetDataSet. + + Attributes: + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDatasetsRequest(proto.Message): + r"""Request message for ListDataset. + + Attributes: + parent (str): + Required. Dataset resource parent, format: + projects/{project_id} + filter (str): + Optional. Filter on dataset is not supported + at this moment. + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by + [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] + of the previous [DataLabelingService.ListDatasets] call. + Returns the first page if empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDatasetsResponse(proto.Message): + r"""Results of listing datasets within a project. + + Attributes: + datasets (Sequence[google.cloud.datalabeling_v1beta1.types.Dataset]): + The list of datasets to return. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + datasets = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_dataset.Dataset, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteDatasetRequest(proto.Message): + r"""Request message for DeleteDataset. + + Attributes: + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ImportDataRequest(proto.Message): + r"""Request message for ImportData API. + + Attributes: + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + input_config (google.cloud.datalabeling_v1beta1.types.InputConfig): + Required. Specify the input source of the + data. + user_email_address (str): + Email of the user who started the import task + and should be notified by email. If empty no + notification will be sent. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_dataset.InputConfig, + ) + user_email_address = proto.Field( + proto.STRING, + number=3, + ) + + +class ExportDataRequest(proto.Message): + r"""Request message for ExportData API. + + Attributes: + name (str): + Required. Dataset resource name, format: + projects/{project_id}/datasets/{dataset_id} + annotated_dataset (str): + Required. Annotated dataset resource name. DataItem in + Dataset and their annotations in specified annotated dataset + will be exported. It's in format of + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + filter (str): + Optional. Filter is not supported at this + moment. + output_config (google.cloud.datalabeling_v1beta1.types.OutputConfig): + Required. Specify the output destination. + user_email_address (str): + Email of the user who started the export task + and should be notified by email. If empty no + notification will be sent. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + annotated_dataset = proto.Field( + proto.STRING, + number=2, + ) + filter = proto.Field( + proto.STRING, + number=3, + ) + output_config = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_dataset.OutputConfig, + ) + user_email_address = proto.Field( + proto.STRING, + number=5, + ) + + +class GetDataItemRequest(proto.Message): + r"""Request message for GetDataItem. + + Attributes: + name (str): + Required. The name of the data item to get, format: + projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDataItemsRequest(proto.Message): + r"""Request message for ListDataItems. + + Attributes: + parent (str): + Required. Name of the dataset to list data items, format: + projects/{project_id}/datasets/{dataset_id} + filter (str): + Optional. Filter is not supported at this + moment. + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by + [ListDataItemsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDataItemsResponse.next_page_token] + of the previous [DataLabelingService.ListDataItems] call. + Return first page if empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDataItemsResponse(proto.Message): + r"""Results of listing data items in a dataset. + + Attributes: + data_items (Sequence[google.cloud.datalabeling_v1beta1.types.DataItem]): + The list of data items to return. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + data_items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_dataset.DataItem, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAnnotatedDatasetRequest(proto.Message): + r"""Request message for GetAnnotatedDataset. + + Attributes: + name (str): + Required. Name of the annotated dataset to get, format: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAnnotatedDatasetsRequest(proto.Message): + r"""Request message for ListAnnotatedDatasets. + + Attributes: + parent (str): + Required. Name of the dataset to list annotated datasets, + format: projects/{project_id}/datasets/{dataset_id} + filter (str): + Optional. Filter is not supported at this + moment. + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by + [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] + of the previous [DataLabelingService.ListAnnotatedDatasets] + call. Return first page if empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnnotatedDatasetsResponse(proto.Message): + r"""Results of listing annotated datasets for a dataset. + + Attributes: + annotated_datasets (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotatedDataset]): + The list of annotated datasets to return. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + annotated_datasets = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_dataset.AnnotatedDataset, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAnnotatedDatasetRequest(proto.Message): + r"""Request message for DeleteAnnotatedDataset. + + Attributes: + name (str): + Required. Name of the annotated dataset to delete, format: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LabelImageRequest(proto.Message): + r"""Request message for starting an image labeling task. + + Attributes: + image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): + Configuration for image classification task. One of + image_classification_config, bounding_poly_config, + polyline_config and segmentation_config are required. + bounding_poly_config (google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig): + Configuration for bounding box and bounding poly task. One + of image_classification_config, bounding_poly_config, + polyline_config and segmentation_config are required. + polyline_config (google.cloud.datalabeling_v1beta1.types.PolylineConfig): + Configuration for polyline task. One of + image_classification_config, bounding_poly_config, + polyline_config and segmentation_config are required. + segmentation_config (google.cloud.datalabeling_v1beta1.types.SegmentationConfig): + Configuration for segmentation task. One of + image_classification_config, bounding_poly_config, + polyline_config and segmentation_config are required. + parent (str): + Required. Name of the dataset to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Required. Basic human annotation config. + feature (google.cloud.datalabeling_v1beta1.types.LabelImageRequest.Feature): + Required. The type of image labeling task. + """ + class Feature(proto.Enum): + r"""Image labeling task feature.""" + FEATURE_UNSPECIFIED = 0 + CLASSIFICATION = 1 + BOUNDING_BOX = 2 + ORIENTED_BOUNDING_BOX = 6 + BOUNDING_POLY = 3 + POLYLINE = 4 + SEGMENTATION = 5 + + image_classification_config = proto.Field( + proto.MESSAGE, + number=4, + oneof='request_config', + message=human_annotation_config.ImageClassificationConfig, + ) + bounding_poly_config = proto.Field( + proto.MESSAGE, + number=5, + oneof='request_config', + message=human_annotation_config.BoundingPolyConfig, + ) + polyline_config = proto.Field( + proto.MESSAGE, + number=6, + oneof='request_config', + message=human_annotation_config.PolylineConfig, + ) + segmentation_config = proto.Field( + proto.MESSAGE, + number=7, + oneof='request_config', + message=human_annotation_config.SegmentationConfig, + ) + parent = proto.Field( + proto.STRING, + number=1, + ) + basic_config = proto.Field( + proto.MESSAGE, + number=2, + message=human_annotation_config.HumanAnnotationConfig, + ) + feature = proto.Field( + proto.ENUM, + number=3, + enum=Feature, + ) + + +class LabelVideoRequest(proto.Message): + r"""Request message for LabelVideo. + + Attributes: + video_classification_config (google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig): + Configuration for video classification task. One of + video_classification_config, object_detection_config, + object_tracking_config and event_config is required. + object_detection_config (google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig): + Configuration for video object detection task. One of + video_classification_config, object_detection_config, + object_tracking_config and event_config is required. + object_tracking_config (google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig): + Configuration for video object tracking task. One of + video_classification_config, object_detection_config, + object_tracking_config and event_config is required. + event_config (google.cloud.datalabeling_v1beta1.types.EventConfig): + Configuration for video event task. One of + video_classification_config, object_detection_config, + object_tracking_config and event_config is required. + parent (str): + Required. Name of the dataset to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Required. Basic human annotation config. + feature (google.cloud.datalabeling_v1beta1.types.LabelVideoRequest.Feature): + Required. The type of video labeling task. + """ + class Feature(proto.Enum): + r"""Video labeling task feature.""" + FEATURE_UNSPECIFIED = 0 + CLASSIFICATION = 1 + OBJECT_DETECTION = 2 + OBJECT_TRACKING = 3 + EVENT = 4 + + video_classification_config = proto.Field( + proto.MESSAGE, + number=4, + oneof='request_config', + message=human_annotation_config.VideoClassificationConfig, + ) + object_detection_config = proto.Field( + proto.MESSAGE, + number=5, + oneof='request_config', + message=human_annotation_config.ObjectDetectionConfig, + ) + object_tracking_config = proto.Field( + proto.MESSAGE, + number=6, + oneof='request_config', + message=human_annotation_config.ObjectTrackingConfig, + ) + event_config = proto.Field( + proto.MESSAGE, + number=7, + oneof='request_config', + message=human_annotation_config.EventConfig, + ) + parent = proto.Field( + proto.STRING, + number=1, + ) + basic_config = proto.Field( + proto.MESSAGE, + number=2, + message=human_annotation_config.HumanAnnotationConfig, + ) + feature = proto.Field( + proto.ENUM, + number=3, + enum=Feature, + ) + + +class LabelTextRequest(proto.Message): + r"""Request message for LabelText. + + Attributes: + text_classification_config (google.cloud.datalabeling_v1beta1.types.TextClassificationConfig): + Configuration for text classification task. One of + text_classification_config and text_entity_extraction_config + is required. + text_entity_extraction_config (google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig): + Configuration for entity extraction task. One of + text_classification_config and text_entity_extraction_config + is required. + parent (str): + Required. Name of the data set to request labeling task, + format: projects/{project_id}/datasets/{dataset_id} + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Required. Basic human annotation config. + feature (google.cloud.datalabeling_v1beta1.types.LabelTextRequest.Feature): + Required. The type of text labeling task. + """ + class Feature(proto.Enum): + r"""Text labeling task feature.""" + FEATURE_UNSPECIFIED = 0 + TEXT_CLASSIFICATION = 1 + TEXT_ENTITY_EXTRACTION = 2 + + text_classification_config = proto.Field( + proto.MESSAGE, + number=4, + oneof='request_config', + message=human_annotation_config.TextClassificationConfig, + ) + text_entity_extraction_config = proto.Field( + proto.MESSAGE, + number=5, + oneof='request_config', + message=human_annotation_config.TextEntityExtractionConfig, + ) + parent = proto.Field( + proto.STRING, + number=1, + ) + basic_config = proto.Field( + proto.MESSAGE, + number=2, + message=human_annotation_config.HumanAnnotationConfig, + ) + feature = proto.Field( + proto.ENUM, + number=6, + enum=Feature, + ) + + +class GetExampleRequest(proto.Message): + r"""Request message for GetExample + + Attributes: + name (str): + Required. Name of example, format: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id}/examples/{example_id} + filter (str): + Optional. An expression for filtering Examples. Filter by + annotation_spec.display_name is supported. Format + "annotation_spec.display_name = {display_name}". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + + +class ListExamplesRequest(proto.Message): + r"""Request message for ListExamples. + + Attributes: + parent (str): + Required. Example resource parent. + filter (str): + Optional. An expression for filtering Examples. For + annotated datasets that have annotation spec set, filter by + annotation_spec.display_name is supported. Format + "annotation_spec.display_name = {display_name}". + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by + [ListExamplesResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListExamplesResponse.next_page_token] + of the previous [DataLabelingService.ListExamples] call. + Return first page if empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListExamplesResponse(proto.Message): + r"""Results of listing Examples in and annotated dataset. + + Attributes: + examples (Sequence[google.cloud.datalabeling_v1beta1.types.Example]): + The list of examples to return. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + examples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_dataset.Example, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAnnotationSpecSetRequest(proto.Message): + r"""Request message for CreateAnnotationSpecSet. + + Attributes: + parent (str): + Required. AnnotationSpecSet resource parent, format: + projects/{project_id} + annotation_spec_set (google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet): + Required. Annotation spec set to create. Annotation specs + must be included. Only one annotation spec will be accepted + for annotation specs with same display_name. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + annotation_spec_set = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_annotation_spec_set.AnnotationSpecSet, + ) + + +class GetAnnotationSpecSetRequest(proto.Message): + r"""Request message for GetAnnotationSpecSet. + + Attributes: + name (str): + Required. AnnotationSpecSet resource name, format: + projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAnnotationSpecSetsRequest(proto.Message): + r"""Request message for ListAnnotationSpecSets. + + Attributes: + parent (str): + Required. Parent of AnnotationSpecSet resource, format: + projects/{project_id} + filter (str): + Optional. Filter is not supported at this + moment. + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by + [ListAnnotationSpecSetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotationSpecSetsResponse.next_page_token] + of the previous [DataLabelingService.ListAnnotationSpecSets] + call. Return first page if empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnnotationSpecSetsResponse(proto.Message): + r"""Results of listing annotation spec set under a project. + + Attributes: + annotation_spec_sets (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet]): + The list of annotation spec sets. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + annotation_spec_sets = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_annotation_spec_set.AnnotationSpecSet, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAnnotationSpecSetRequest(proto.Message): + r"""Request message for DeleteAnnotationSpecSet. + + Attributes: + name (str): + Required. AnnotationSpec resource name, format: + ``projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateInstructionRequest(proto.Message): + r"""Request message for CreateInstruction. + + Attributes: + parent (str): + Required. Instruction resource parent, format: + projects/{project_id} + instruction (google.cloud.datalabeling_v1beta1.types.Instruction): + Required. Instruction of how to perform the + labeling task. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + instruction = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_instruction.Instruction, + ) + + +class GetInstructionRequest(proto.Message): + r"""Request message for GetInstruction. + + Attributes: + name (str): + Required. Instruction resource name, format: + projects/{project_id}/instructions/{instruction_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteInstructionRequest(proto.Message): + r"""Request message for DeleteInstruction. + + Attributes: + name (str): + Required. Instruction resource name, format: + projects/{project_id}/instructions/{instruction_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListInstructionsRequest(proto.Message): + r"""Request message for ListInstructions. + + Attributes: + parent (str): + Required. Instruction resource parent, format: + projects/{project_id} + filter (str): + Optional. Filter is not supported at this + moment. + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by + [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] + of the previous [DataLabelingService.ListInstructions] call. + Return first page if empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListInstructionsResponse(proto.Message): + r"""Results of listing instructions under a project. + + Attributes: + instructions (Sequence[google.cloud.datalabeling_v1beta1.types.Instruction]): + The list of Instructions to return. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + instructions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_instruction.Instruction, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEvaluationRequest(proto.Message): + r"""Request message for GetEvaluation. + + Attributes: + name (str): + Required. Name of the evaluation. Format: + + "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class SearchEvaluationsRequest(proto.Message): + r"""Request message for SearchEvaluation. + + Attributes: + parent (str): + Required. Evaluation search parent (project ID). Format: + "projects/{project_id}". + filter (str): + Optional. To search evaluations, you can filter by the + following: + + - evaluation\_job.evaluation_job_id (the last part of + [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) + - evaluation\_job.model_id (the {model_name} portion of + [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) + - evaluation\_job.evaluation_job_run_time_start (Minimum + threshold for the + [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] + that created the evaluation) + - evaluation\_job.evaluation_job_run_time_end (Maximum + threshold for the + [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] + that created the evaluation) + - evaluation\_job.job_state + ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) + - annotation\_spec.display_name (the Evaluation contains a + metric for the annotation spec with this + [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) + + To filter by multiple critiera, use the ``AND`` operator or + the ``OR`` operator. The following examples shows a string + that filters by several critiera: + + "evaluation\ *job.evaluation_job_id = {evaluation_job_id} + AND evaluation*\ job.model_id = {model_name} AND + evaluation\ *job.evaluation_job_run_time_start = + {timestamp_1} AND + evaluation*\ job.evaluation_job_run_time_end = {timestamp_2} + AND annotation\_spec.display_name = {display_name}". + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by the + [nextPageToken][google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.next_page_token] + of the response to a previous search request. + + If you don't specify this field, the API call requests the + first page of the search. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchEvaluationsResponse(proto.Message): + r"""Results of searching evaluations. + + Attributes: + evaluations (Sequence[google.cloud.datalabeling_v1beta1.types.Evaluation]): + The list of evaluations matching the search. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + evaluations = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=evaluation.Evaluation, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchExampleComparisonsRequest(proto.Message): + r"""Request message of SearchExampleComparisons. + + Attributes: + parent (str): + Required. Name of the + [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] + resource to search for example comparisons from. Format: + + "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}". + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by the + [nextPageToken][SearchExampleComparisons.next_page_token] of + the response to a previous search rquest. + + If you don't specify this field, the API call requests the + first page of the search. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class SearchExampleComparisonsResponse(proto.Message): + r"""Results of searching example comparisons. + + Attributes: + example_comparisons (Sequence[google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse.ExampleComparison]): + A list of example comparisons matching the + search criteria. + next_page_token (str): + A token to retrieve next page of results. + """ + + class ExampleComparison(proto.Message): + r"""Example comparisons comparing ground truth output and + predictions for a specific input. + + Attributes: + ground_truth_example (google.cloud.datalabeling_v1beta1.types.Example): + The ground truth output for the input. + model_created_examples (Sequence[google.cloud.datalabeling_v1beta1.types.Example]): + Predictions by the model for the input. + """ + + ground_truth_example = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_dataset.Example, + ) + model_created_examples = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcd_dataset.Example, + ) + + @property + def raw_page(self): + return self + + example_comparisons = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ExampleComparison, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEvaluationJobRequest(proto.Message): + r"""Request message for CreateEvaluationJob. + + Attributes: + parent (str): + Required. Evaluation job resource parent. Format: + "projects/{project_id}". + job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): + Required. The evaluation job to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + job = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_evaluation_job.EvaluationJob, + ) + + +class UpdateEvaluationJobRequest(proto.Message): + r"""Request message for UpdateEvaluationJob. + + Attributes: + evaluation_job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): + Required. Evaluation job that is going to be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Mask for which fields to update. You can only + provide the following fields: + + - ``evaluationJobConfig.humanAnnotationConfig.instruction`` + - ``evaluationJobConfig.exampleCount`` + - ``evaluationJobConfig.exampleSamplePercentage`` + + You can provide more than one of these fields by separating + them with commas. + """ + + evaluation_job = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_evaluation_job.EvaluationJob, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetEvaluationJobRequest(proto.Message): + r"""Request message for GetEvaluationJob. + + Attributes: + name (str): + Required. Name of the evaluation job. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class PauseEvaluationJobRequest(proto.Message): + r"""Request message for PauseEvaluationJob. + + Attributes: + name (str): + Required. Name of the evaluation job that is going to be + paused. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ResumeEvaluationJobRequest(proto.Message): + r"""Request message ResumeEvaluationJob. + + Attributes: + name (str): + Required. Name of the evaluation job that is going to be + resumed. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteEvaluationJobRequest(proto.Message): + r"""Request message DeleteEvaluationJob. + + Attributes: + name (str): + Required. Name of the evaluation job that is going to be + deleted. Format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEvaluationJobsRequest(proto.Message): + r"""Request message for ListEvaluationJobs. + + Attributes: + parent (str): + Required. Evaluation job resource parent. Format: + "projects/{project_id}". + filter (str): + Optional. You can filter the jobs to list by model_id (also + known as model_name, as described in + [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) + or by evaluation job state (as described in + [EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]). + To filter by both criteria, use the ``AND`` operator or the + ``OR`` operator. For example, you can use the following + string for your filter: "evaluation\ *job.model_id = + {model_name} AND evaluation*\ job.state = + {evaluation_job_state}". + page_size (int): + Optional. Requested page size. Server may + return fewer results than requested. Default + value is 100. + page_token (str): + Optional. A token identifying a page of results for the + server to return. Typically obtained by the + [nextPageToken][google.cloud.datalabeling.v1beta1.ListEvaluationJobsResponse.next_page_token] + in the response to the previous request. The request returns + the first page if this is empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEvaluationJobsResponse(proto.Message): + r"""Results for listing evaluation jobs. + + Attributes: + evaluation_jobs (Sequence[google.cloud.datalabeling_v1beta1.types.EvaluationJob]): + The list of evaluation jobs to return. + next_page_token (str): + A token to retrieve next page of results. + """ + + @property + def raw_page(self): + return self + + evaluation_jobs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_evaluation_job.EvaluationJob, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py new file mode 100644 index 0000000..bba9a8c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py @@ -0,0 +1,142 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'ImagePayload', + 'TextPayload', + 'VideoThumbnail', + 'VideoPayload', + }, +) + + +class ImagePayload(proto.Message): + r"""Container of information about an image. + + Attributes: + mime_type (str): + Image format. + image_thumbnail (bytes): + A byte string of a thumbnail image. + image_uri (str): + Image uri from the user bucket. + signed_uri (str): + Signed uri of the image file in the service + bucket. + """ + + mime_type = proto.Field( + proto.STRING, + number=1, + ) + image_thumbnail = proto.Field( + proto.BYTES, + number=2, + ) + image_uri = proto.Field( + proto.STRING, + number=3, + ) + signed_uri = proto.Field( + proto.STRING, + number=4, + ) + + +class TextPayload(proto.Message): + r"""Container of information about a piece of text. + + Attributes: + text_content (str): + Text content. + """ + + text_content = proto.Field( + proto.STRING, + number=1, + ) + + +class VideoThumbnail(proto.Message): + r"""Container of information of a video thumbnail. + + Attributes: + thumbnail (bytes): + A byte string of the video frame. + time_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the + video, corresponding to the video frame where + the thumbnail has been extracted from. + """ + + thumbnail = proto.Field( + proto.BYTES, + number=1, + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class VideoPayload(proto.Message): + r"""Container of information of a video. + + Attributes: + mime_type (str): + Video format. + video_uri (str): + Video uri from the user bucket. + video_thumbnails (Sequence[google.cloud.datalabeling_v1beta1.types.VideoThumbnail]): + The list of video thumbnails. + frame_rate (float): + FPS of the video. + signed_uri (str): + Signed uri of the video file in the service + bucket. + """ + + mime_type = proto.Field( + proto.STRING, + number=1, + ) + video_uri = proto.Field( + proto.STRING, + number=2, + ) + video_thumbnails = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='VideoThumbnail', + ) + frame_rate = proto.Field( + proto.FLOAT, + number=4, + ) + signed_uri = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py new file mode 100644 index 0000000..b7099d4 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py @@ -0,0 +1,645 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.datalabeling_v1beta1.types import annotation +from google.cloud.datalabeling_v1beta1.types import data_payloads +from google.cloud.datalabeling_v1beta1.types import human_annotation_config as gcd_human_annotation_config +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'DataType', + 'Dataset', + 'InputConfig', + 'TextMetadata', + 'ClassificationMetadata', + 'GcsSource', + 'BigQuerySource', + 'OutputConfig', + 'GcsDestination', + 'GcsFolderDestination', + 'DataItem', + 'AnnotatedDataset', + 'LabelStats', + 'AnnotatedDatasetMetadata', + 'Example', + }, +) + + +class DataType(proto.Enum): + r"""""" + DATA_TYPE_UNSPECIFIED = 0 + IMAGE = 1 + VIDEO = 2 + TEXT = 4 + GENERAL_DATA = 6 + + +class Dataset(proto.Message): + r"""Dataset is the resource to hold your data. You can request + multiple labeling tasks for a dataset while each one will + generate an AnnotatedDataset. + + Attributes: + name (str): + Output only. Dataset resource name, format is: + projects/{project_id}/datasets/{dataset_id} + display_name (str): + Required. The display name of the dataset. + Maximum of 64 characters. + description (str): + Optional. User-provided description of the + annotation specification set. The description + can be up to 10000 characters long. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the dataset is created. + input_configs (Sequence[google.cloud.datalabeling_v1beta1.types.InputConfig]): + Output only. This is populated with the + original input configs where ImportData is + called. It is available only after the clients + import data to this dataset. + blocking_resources (Sequence[str]): + Output only. The names of any related + resources that are blocking changes to the + dataset. + data_item_count (int): + Output only. The number of data items in the + dataset. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + input_configs = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='InputConfig', + ) + blocking_resources = proto.RepeatedField( + proto.STRING, + number=6, + ) + data_item_count = proto.Field( + proto.INT64, + number=7, + ) + + +class InputConfig(proto.Message): + r"""The configuration of input data, including data type, + location, etc. + + Attributes: + text_metadata (google.cloud.datalabeling_v1beta1.types.TextMetadata): + Required for text import, as language code + must be specified. + gcs_source (google.cloud.datalabeling_v1beta1.types.GcsSource): + Source located in Cloud Storage. + bigquery_source (google.cloud.datalabeling_v1beta1.types.BigQuerySource): + Source located in BigQuery. You must specify this field if + you are using this InputConfig in an + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob]. + data_type (google.cloud.datalabeling_v1beta1.types.DataType): + Required. Data type must be specifed when + user tries to import data. + annotation_type (google.cloud.datalabeling_v1beta1.types.AnnotationType): + Optional. The type of annotation to be performed on this + data. You must specify this field if you are using this + InputConfig in an + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob]. + classification_metadata (google.cloud.datalabeling_v1beta1.types.ClassificationMetadata): + Optional. Metadata about annotations for the input. You must + specify this field if you are using this InputConfig in an + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] + for a model version that performs classification. + """ + + text_metadata = proto.Field( + proto.MESSAGE, + number=6, + oneof='data_type_metadata', + message='TextMetadata', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + bigquery_source = proto.Field( + proto.MESSAGE, + number=5, + oneof='source', + message='BigQuerySource', + ) + data_type = proto.Field( + proto.ENUM, + number=1, + enum='DataType', + ) + annotation_type = proto.Field( + proto.ENUM, + number=3, + enum=annotation.AnnotationType, + ) + classification_metadata = proto.Field( + proto.MESSAGE, + number=4, + message='ClassificationMetadata', + ) + + +class TextMetadata(proto.Message): + r"""Metadata for the text. + + Attributes: + language_code (str): + The language of this text, as a + `BCP-47 `__. + Default value is en-US. + """ + + language_code = proto.Field( + proto.STRING, + number=1, + ) + + +class ClassificationMetadata(proto.Message): + r"""Metadata for classification annotations. + + Attributes: + is_multi_label (bool): + Whether the classification task is multi- + abel or not. + """ + + is_multi_label = proto.Field( + proto.BOOL, + number=1, + ) + + +class GcsSource(proto.Message): + r"""Source of the Cloud Storage file to be imported. + + Attributes: + input_uri (str): + Required. The input URI of source file. This must be a Cloud + Storage path (``gs://...``). + mime_type (str): + Required. The format of the source file. Only + "text/csv" is supported. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + mime_type = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""The BigQuery location for input data. If used in an + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob], + this is where the service saves the prediction input and output + sampled from the model version. + + Attributes: + input_uri (str): + Required. BigQuery URI to a table, up to 2,000 characters + long. If you specify the URI of a table that does not exist, + Data Labeling Service creates a table at the URI with the + correct schema when you create your + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob]. + If you specify the URI of a table that already exists, it + must have the `correct + schema `__. + + Provide the table URI in the following format: + + "bq://{your_project_id}/{your_dataset_name}/{your_table_name}" + + `Learn + more `__. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + + +class OutputConfig(proto.Message): + r"""The configuration of output data. + + Attributes: + gcs_destination (google.cloud.datalabeling_v1beta1.types.GcsDestination): + Output to a file in Cloud Storage. Should be + used for labeling output other than image + segmentation. + gcs_folder_destination (google.cloud.datalabeling_v1beta1.types.GcsFolderDestination): + Output to a folder in Cloud Storage. Should + be used for image segmentation labeling output. + """ + + gcs_destination = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + gcs_folder_destination = proto.Field( + proto.MESSAGE, + number=2, + oneof='destination', + message='GcsFolderDestination', + ) + + +class GcsDestination(proto.Message): + r"""Export destination of the data.Only gcs path is allowed in + output_uri. + + Attributes: + output_uri (str): + Required. The output uri of destination file. + mime_type (str): + Required. The format of the gcs destination. + Only "text/csv" and "application/json" + are supported. + """ + + output_uri = proto.Field( + proto.STRING, + number=1, + ) + mime_type = proto.Field( + proto.STRING, + number=2, + ) + + +class GcsFolderDestination(proto.Message): + r"""Export folder destination of the data. + + Attributes: + output_folder_uri (str): + Required. Cloud Storage directory to export + data to. + """ + + output_folder_uri = proto.Field( + proto.STRING, + number=1, + ) + + +class DataItem(proto.Message): + r"""DataItem is a piece of data, without annotation. For example, + an image. + + Attributes: + image_payload (google.cloud.datalabeling_v1beta1.types.ImagePayload): + The image payload, a container of the image + bytes/uri. + text_payload (google.cloud.datalabeling_v1beta1.types.TextPayload): + The text payload, a container of text + content. + video_payload (google.cloud.datalabeling_v1beta1.types.VideoPayload): + The video payload, a container of the video + uri. + name (str): + Output only. Name of the data item, in format of: + projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} + """ + + image_payload = proto.Field( + proto.MESSAGE, + number=2, + oneof='payload', + message=data_payloads.ImagePayload, + ) + text_payload = proto.Field( + proto.MESSAGE, + number=3, + oneof='payload', + message=data_payloads.TextPayload, + ) + video_payload = proto.Field( + proto.MESSAGE, + number=4, + oneof='payload', + message=data_payloads.VideoPayload, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + + +class AnnotatedDataset(proto.Message): + r"""AnnotatedDataset is a set holding annotations for data in a + Dataset. Each labeling task will generate an AnnotatedDataset + under the Dataset that the task is requested for. + + Attributes: + name (str): + Output only. AnnotatedDataset resource name in format of: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id} + display_name (str): + Output only. The display name of the + AnnotatedDataset. It is specified in + HumanAnnotationConfig when user starts a + labeling task. Maximum of 64 characters. + description (str): + Output only. The description of the + AnnotatedDataset. It is specified in + HumanAnnotationConfig when user starts a + labeling task. Maximum of 10000 characters. + annotation_source (google.cloud.datalabeling_v1beta1.types.AnnotationSource): + Output only. Source of the annotation. + annotation_type (google.cloud.datalabeling_v1beta1.types.AnnotationType): + Output only. Type of the annotation. It is + specified when starting labeling task. + example_count (int): + Output only. Number of examples in the + annotated dataset. + completed_example_count (int): + Output only. Number of examples that have + annotation in the annotated dataset. + label_stats (google.cloud.datalabeling_v1beta1.types.LabelStats): + Output only. Per label statistics. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the AnnotatedDataset was + created. + metadata (google.cloud.datalabeling_v1beta1.types.AnnotatedDatasetMetadata): + Output only. Additional information about + AnnotatedDataset. + blocking_resources (Sequence[str]): + Output only. The names of any related + resources that are blocking changes to the + annotated dataset. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=9, + ) + annotation_source = proto.Field( + proto.ENUM, + number=3, + enum=annotation.AnnotationSource, + ) + annotation_type = proto.Field( + proto.ENUM, + number=8, + enum=annotation.AnnotationType, + ) + example_count = proto.Field( + proto.INT64, + number=4, + ) + completed_example_count = proto.Field( + proto.INT64, + number=5, + ) + label_stats = proto.Field( + proto.MESSAGE, + number=6, + message='LabelStats', + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + metadata = proto.Field( + proto.MESSAGE, + number=10, + message='AnnotatedDatasetMetadata', + ) + blocking_resources = proto.RepeatedField( + proto.STRING, + number=11, + ) + + +class LabelStats(proto.Message): + r"""Statistics about annotation specs. + + Attributes: + example_count (Sequence[google.cloud.datalabeling_v1beta1.types.LabelStats.ExampleCountEntry]): + Map of each annotation spec's example count. + Key is the annotation spec name and value is the + number of examples for that annotation spec. If + the annotated dataset does not have annotation + spec, the map will return a pair where the key + is empty string and value is the total number of + annotations. + """ + + example_count = proto.MapField( + proto.STRING, + proto.INT64, + number=1, + ) + + +class AnnotatedDatasetMetadata(proto.Message): + r"""Metadata on AnnotatedDataset. + + Attributes: + image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): + Configuration for image classification task. + bounding_poly_config (google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig): + Configuration for image bounding box and + bounding poly task. + polyline_config (google.cloud.datalabeling_v1beta1.types.PolylineConfig): + Configuration for image polyline task. + segmentation_config (google.cloud.datalabeling_v1beta1.types.SegmentationConfig): + Configuration for image segmentation task. + video_classification_config (google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig): + Configuration for video classification task. + object_detection_config (google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig): + Configuration for video object detection + task. + object_tracking_config (google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig): + Configuration for video object tracking task. + event_config (google.cloud.datalabeling_v1beta1.types.EventConfig): + Configuration for video event labeling task. + text_classification_config (google.cloud.datalabeling_v1beta1.types.TextClassificationConfig): + Configuration for text classification task. + text_entity_extraction_config (google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig): + Configuration for text entity extraction + task. + human_annotation_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + HumanAnnotationConfig used when requesting + the human labeling task for this + AnnotatedDataset. + """ + + image_classification_config = proto.Field( + proto.MESSAGE, + number=2, + oneof='annotation_request_config', + message=gcd_human_annotation_config.ImageClassificationConfig, + ) + bounding_poly_config = proto.Field( + proto.MESSAGE, + number=3, + oneof='annotation_request_config', + message=gcd_human_annotation_config.BoundingPolyConfig, + ) + polyline_config = proto.Field( + proto.MESSAGE, + number=4, + oneof='annotation_request_config', + message=gcd_human_annotation_config.PolylineConfig, + ) + segmentation_config = proto.Field( + proto.MESSAGE, + number=5, + oneof='annotation_request_config', + message=gcd_human_annotation_config.SegmentationConfig, + ) + video_classification_config = proto.Field( + proto.MESSAGE, + number=6, + oneof='annotation_request_config', + message=gcd_human_annotation_config.VideoClassificationConfig, + ) + object_detection_config = proto.Field( + proto.MESSAGE, + number=7, + oneof='annotation_request_config', + message=gcd_human_annotation_config.ObjectDetectionConfig, + ) + object_tracking_config = proto.Field( + proto.MESSAGE, + number=8, + oneof='annotation_request_config', + message=gcd_human_annotation_config.ObjectTrackingConfig, + ) + event_config = proto.Field( + proto.MESSAGE, + number=9, + oneof='annotation_request_config', + message=gcd_human_annotation_config.EventConfig, + ) + text_classification_config = proto.Field( + proto.MESSAGE, + number=10, + oneof='annotation_request_config', + message=gcd_human_annotation_config.TextClassificationConfig, + ) + text_entity_extraction_config = proto.Field( + proto.MESSAGE, + number=11, + oneof='annotation_request_config', + message=gcd_human_annotation_config.TextEntityExtractionConfig, + ) + human_annotation_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_human_annotation_config.HumanAnnotationConfig, + ) + + +class Example(proto.Message): + r"""An Example is a piece of data and its annotation. For + example, an image with label "house". + + Attributes: + image_payload (google.cloud.datalabeling_v1beta1.types.ImagePayload): + The image payload, a container of the image + bytes/uri. + text_payload (google.cloud.datalabeling_v1beta1.types.TextPayload): + The text payload, a container of the text + content. + video_payload (google.cloud.datalabeling_v1beta1.types.VideoPayload): + The video payload, a container of the video + uri. + name (str): + Output only. Name of the example, in format of: + projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ + {annotated_dataset_id}/examples/{example_id} + annotations (Sequence[google.cloud.datalabeling_v1beta1.types.Annotation]): + Output only. Annotations for the piece of + data in Example. One piece of data can have + multiple annotations. + """ + + image_payload = proto.Field( + proto.MESSAGE, + number=2, + oneof='payload', + message=data_payloads.ImagePayload, + ) + text_payload = proto.Field( + proto.MESSAGE, + number=6, + oneof='payload', + message=data_payloads.TextPayload, + ) + video_payload = proto.Field( + proto.MESSAGE, + number=7, + oneof='payload', + message=data_payloads.VideoPayload, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + annotations = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=annotation.Annotation, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py new file mode 100644 index 0000000..c34524a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py @@ -0,0 +1,405 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.datalabeling_v1beta1.types import annotation +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'Evaluation', + 'EvaluationConfig', + 'BoundingBoxEvaluationOptions', + 'EvaluationMetrics', + 'ClassificationMetrics', + 'ObjectDetectionMetrics', + 'PrCurve', + 'ConfusionMatrix', + }, +) + + +class Evaluation(proto.Message): + r"""Describes an evaluation between a machine learning model's + predictions and ground truth labels. Created when an + [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] + runs successfully. + + Attributes: + name (str): + Output only. Resource name of an evaluation. The name has + the following format: + + "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' + config (google.cloud.datalabeling_v1beta1.types.EvaluationConfig): + Output only. Options used in the evaluation + job that created this evaluation. + evaluation_job_run_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp for when the + evaluation job that created this evaluation ran. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp for when this + evaluation was created. + evaluation_metrics (google.cloud.datalabeling_v1beta1.types.EvaluationMetrics): + Output only. Metrics comparing predictions to + ground truth labels. + annotation_type (google.cloud.datalabeling_v1beta1.types.AnnotationType): + Output only. Type of task that the model version being + evaluated performs, as defined in the + + [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config] + field of the evaluation job that created this evaluation. + evaluated_item_count (int): + Output only. The number of items in the + ground truth dataset that were used for this + evaluation. Only populated when the evaulation + is for certain AnnotationTypes. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + config = proto.Field( + proto.MESSAGE, + number=2, + message='EvaluationConfig', + ) + evaluation_job_run_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + evaluation_metrics = proto.Field( + proto.MESSAGE, + number=5, + message='EvaluationMetrics', + ) + annotation_type = proto.Field( + proto.ENUM, + number=6, + enum=annotation.AnnotationType, + ) + evaluated_item_count = proto.Field( + proto.INT64, + number=7, + ) + + +class EvaluationConfig(proto.Message): + r"""Configuration details used for calculating evaluation metrics and + creating an + [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation]. + + Attributes: + bounding_box_evaluation_options (google.cloud.datalabeling_v1beta1.types.BoundingBoxEvaluationOptions): + Only specify this field if the related model performs image + object detection (``IMAGE_BOUNDING_BOX_ANNOTATION``). + Describes how to evaluate bounding boxes. + """ + + bounding_box_evaluation_options = proto.Field( + proto.MESSAGE, + number=1, + oneof='vertical_option', + message='BoundingBoxEvaluationOptions', + ) + + +class BoundingBoxEvaluationOptions(proto.Message): + r"""Options regarding evaluation between bounding boxes. + + Attributes: + iou_threshold (float): + Minimum [intersection-over-union + + (IOU)](/vision/automl/object-detection/docs/evaluate#intersection-over-union) + required for 2 bounding boxes to be considered a match. This + must be a number between 0 and 1. + """ + + iou_threshold = proto.Field( + proto.FLOAT, + number=1, + ) + + +class EvaluationMetrics(proto.Message): + r""" + + Attributes: + classification_metrics (google.cloud.datalabeling_v1beta1.types.ClassificationMetrics): + + object_detection_metrics (google.cloud.datalabeling_v1beta1.types.ObjectDetectionMetrics): + + """ + + classification_metrics = proto.Field( + proto.MESSAGE, + number=1, + oneof='metrics', + message='ClassificationMetrics', + ) + object_detection_metrics = proto.Field( + proto.MESSAGE, + number=2, + oneof='metrics', + message='ObjectDetectionMetrics', + ) + + +class ClassificationMetrics(proto.Message): + r"""Metrics calculated for a classification model. + + Attributes: + pr_curve (google.cloud.datalabeling_v1beta1.types.PrCurve): + Precision-recall curve based on ground truth + labels, predicted labels, and scores for the + predicted labels. + confusion_matrix (google.cloud.datalabeling_v1beta1.types.ConfusionMatrix): + Confusion matrix of predicted labels vs. + ground truth labels. + """ + + pr_curve = proto.Field( + proto.MESSAGE, + number=1, + message='PrCurve', + ) + confusion_matrix = proto.Field( + proto.MESSAGE, + number=2, + message='ConfusionMatrix', + ) + + +class ObjectDetectionMetrics(proto.Message): + r"""Metrics calculated for an image object detection (bounding + box) model. + + Attributes: + pr_curve (google.cloud.datalabeling_v1beta1.types.PrCurve): + Precision-recall curve. + """ + + pr_curve = proto.Field( + proto.MESSAGE, + number=1, + message='PrCurve', + ) + + +class PrCurve(proto.Message): + r""" + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + The annotation spec of the label for which + the precision-recall curve calculated. If this + field is empty, that means the precision-recall + curve is an aggregate curve for all labels. + area_under_curve (float): + Area under the precision-recall curve. Not to + be confused with area under a receiver operating + characteristic (ROC) curve. + confidence_metrics_entries (Sequence[google.cloud.datalabeling_v1beta1.types.PrCurve.ConfidenceMetricsEntry]): + Entries that make up the precision-recall graph. Each entry + is a "point" on the graph drawn for a different + ``confidence_threshold``. + mean_average_precision (float): + Mean average prcision of this curve. + """ + + class ConfidenceMetricsEntry(proto.Message): + r""" + + Attributes: + confidence_threshold (float): + Threshold used for this entry. + + For classification tasks, this is a classification + threshold: a predicted label is categorized as positive or + negative (in the context of this point on the PR curve) + based on whether the label's score meets this threshold. + + For image object detection (bounding box) tasks, this is the + [intersection-over-union + + (IOU)](/vision/automl/object-detection/docs/evaluate#intersection-over-union) + threshold for the context of this point on the PR curve. + recall (float): + Recall value. + precision (float): + Precision value. + f1_score (float): + Harmonic mean of recall and precision. + recall_at1 (float): + Recall value for entries with label that has + highest score. + precision_at1 (float): + Precision value for entries with label that + has highest score. + f1_score_at1 (float): + The harmonic mean of + [recall_at1][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.recall_at1] + and + [precision_at1][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.precision_at1]. + recall_at5 (float): + Recall value for entries with label that has + highest 5 scores. + precision_at5 (float): + Precision value for entries with label that + has highest 5 scores. + f1_score_at5 (float): + The harmonic mean of + [recall_at5][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.recall_at5] + and + [precision_at5][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.precision_at5]. + """ + + confidence_threshold = proto.Field( + proto.FLOAT, + number=1, + ) + recall = proto.Field( + proto.FLOAT, + number=2, + ) + precision = proto.Field( + proto.FLOAT, + number=3, + ) + f1_score = proto.Field( + proto.FLOAT, + number=4, + ) + recall_at1 = proto.Field( + proto.FLOAT, + number=5, + ) + precision_at1 = proto.Field( + proto.FLOAT, + number=6, + ) + f1_score_at1 = proto.Field( + proto.FLOAT, + number=7, + ) + recall_at5 = proto.Field( + proto.FLOAT, + number=8, + ) + precision_at5 = proto.Field( + proto.FLOAT, + number=9, + ) + f1_score_at5 = proto.Field( + proto.FLOAT, + number=10, + ) + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + area_under_curve = proto.Field( + proto.FLOAT, + number=2, + ) + confidence_metrics_entries = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ConfidenceMetricsEntry, + ) + mean_average_precision = proto.Field( + proto.FLOAT, + number=4, + ) + + +class ConfusionMatrix(proto.Message): + r"""Confusion matrix of the model running the classification. + Only applicable when the metrics entry aggregates multiple + labels. Not applicable when the entry is for a single label. + + Attributes: + row (Sequence[google.cloud.datalabeling_v1beta1.types.ConfusionMatrix.Row]): + + """ + + class ConfusionMatrixEntry(proto.Message): + r""" + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + The annotation spec of a predicted label. + item_count (int): + Number of items predicted to have this label. (The ground + truth label for these items is the ``Row.annotationSpec`` of + this entry's parent.) + """ + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + item_count = proto.Field( + proto.INT32, + number=2, + ) + + class Row(proto.Message): + r"""A row in the confusion matrix. Each entry in this row has the + same ground truth label. + + Attributes: + annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): + The annotation spec of the ground truth label + for this row. + entries (Sequence[google.cloud.datalabeling_v1beta1.types.ConfusionMatrix.ConfusionMatrixEntry]): + A list of the confusion matrix entries. One + entry for each possible predicted label. + """ + + annotation_spec = proto.Field( + proto.MESSAGE, + number=1, + message=annotation_spec_set.AnnotationSpec, + ) + entries = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ConfusionMatrix.ConfusionMatrixEntry', + ) + + row = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Row, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py new file mode 100644 index 0000000..88c9624 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py @@ -0,0 +1,375 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import human_annotation_config as gcd_human_annotation_config +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'EvaluationJob', + 'EvaluationJobConfig', + 'EvaluationJobAlertConfig', + 'Attempt', + }, +) + + +class EvaluationJob(proto.Message): + r"""Defines an evaluation job that runs periodically to generate + [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. + `Creating an evaluation + job `__ is the + starting point for using continuous evaluation. + + Attributes: + name (str): + Output only. After you create a job, Data Labeling Service + assigns a name to the job with the following format: + + "projects/{project_id}/evaluationJobs/{evaluation_job_id}". + description (str): + Required. Description of the job. The + description can be up to 25,000 characters long. + state (google.cloud.datalabeling_v1beta1.types.EvaluationJob.State): + Output only. Describes the current state of + the job. + schedule (str): + Required. Describes the interval at which the job runs. This + interval must be at least 1 day, and it is rounded to the + nearest day. For example, if you specify a 50-hour interval, + the job runs every 2 days. + + You can provide the schedule in `crontab + format `__ + or in an `English-like + format `__. + + Regardless of what you specify, the job will run at 10:00 AM + UTC. Only the interval from this schedule is used, not the + specific time of day. + model_version (str): + Required. The `AI Platform Prediction model + version `__ to be + evaluated. Prediction input and output is sampled from this + model version. When creating an evaluation job, specify the + model version in the following format: + + "projects/{project_id}/models/{model_name}/versions/{version_name}" + + There can only be one evaluation job per model version. + evaluation_job_config (google.cloud.datalabeling_v1beta1.types.EvaluationJobConfig): + Required. Configuration details for the + evaluation job. + annotation_spec_set (str): + Required. Name of the + [AnnotationSpecSet][google.cloud.datalabeling.v1beta1.AnnotationSpecSet] + describing all the labels that your machine learning model + outputs. You must create this resource before you create an + evaluation job and provide its name in the following format: + + "projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}". + label_missing_ground_truth (bool): + Required. Whether you want Data Labeling Service to provide + ground truth labels for prediction input. If you want the + service to assign human labelers to annotate your data, set + this to ``true``. If you want to provide your own ground + truth labels in the evaluation job's BigQuery table, set + this to ``false``. + attempts (Sequence[google.cloud.datalabeling_v1beta1.types.Attempt]): + Output only. Every time the evaluation job + runs and an error occurs, the failed attempt is + appended to this array. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp of when this + evaluation job was created. + """ + class State(proto.Enum): + r"""State of the job.""" + STATE_UNSPECIFIED = 0 + SCHEDULED = 1 + RUNNING = 2 + PAUSED = 3 + STOPPED = 4 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + schedule = proto.Field( + proto.STRING, + number=4, + ) + model_version = proto.Field( + proto.STRING, + number=5, + ) + evaluation_job_config = proto.Field( + proto.MESSAGE, + number=6, + message='EvaluationJobConfig', + ) + annotation_spec_set = proto.Field( + proto.STRING, + number=7, + ) + label_missing_ground_truth = proto.Field( + proto.BOOL, + number=8, + ) + attempts = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Attempt', + ) + create_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class EvaluationJobConfig(proto.Message): + r"""Configures specific details of how a continuous evaluation + job works. Provide this configuration when you create an + EvaluationJob. + + Attributes: + image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): + Specify this field if your model version performs image + classification or general classification. + + ``annotationSpecSet`` in this configuration must match + [EvaluationJob.annotationSpecSet][google.cloud.datalabeling.v1beta1.EvaluationJob.annotation_spec_set]. + ``allowMultiLabel`` in this configuration must match + ``classificationMetadata.isMultiLabel`` in + [input_config][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]. + bounding_poly_config (google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig): + Specify this field if your model version performs image + object detection (bounding box detection). + + ``annotationSpecSet`` in this configuration must match + [EvaluationJob.annotationSpecSet][google.cloud.datalabeling.v1beta1.EvaluationJob.annotation_spec_set]. + text_classification_config (google.cloud.datalabeling_v1beta1.types.TextClassificationConfig): + Specify this field if your model version performs text + classification. + + ``annotationSpecSet`` in this configuration must match + [EvaluationJob.annotationSpecSet][google.cloud.datalabeling.v1beta1.EvaluationJob.annotation_spec_set]. + ``allowMultiLabel`` in this configuration must match + ``classificationMetadata.isMultiLabel`` in + [input_config][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]. + input_config (google.cloud.datalabeling_v1beta1.types.InputConfig): + Rquired. Details for the sampled prediction input. Within + this configuration, there are requirements for several + fields: + + - ``dataType`` must be one of ``IMAGE``, ``TEXT``, or + ``GENERAL_DATA``. + - ``annotationType`` must be one of + ``IMAGE_CLASSIFICATION_ANNOTATION``, + ``TEXT_CLASSIFICATION_ANNOTATION``, + ``GENERAL_CLASSIFICATION_ANNOTATION``, or + ``IMAGE_BOUNDING_BOX_ANNOTATION`` (image object + detection). + - If your machine learning model performs classification, + you must specify ``classificationMetadata.isMultiLabel``. + - You must specify ``bigquerySource`` (not ``gcsSource``). + evaluation_config (google.cloud.datalabeling_v1beta1.types.EvaluationConfig): + Required. Details for calculating evaluation metrics and + creating + [Evaulations][google.cloud.datalabeling.v1beta1.Evaluation]. + If your model version performs image object detection, you + must specify the ``boundingBoxEvaluationOptions`` field + within this configuration. Otherwise, provide an empty + object for this configuration. + human_annotation_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Optional. Details for human annotation of your data. If you + set + [labelMissingGroundTruth][google.cloud.datalabeling.v1beta1.EvaluationJob.label_missing_ground_truth] + to ``true`` for this evaluation job, then you must specify + this field. If you plan to provide your own ground truth + labels, then omit this field. + + Note that you must create an + [Instruction][google.cloud.datalabeling.v1beta1.Instruction] + resource before you can specify this field. Provide the name + of the instruction resource in the ``instruction`` field + within this configuration. + bigquery_import_keys (Sequence[google.cloud.datalabeling_v1beta1.types.EvaluationJobConfig.BigqueryImportKeysEntry]): + Required. Prediction keys that tell Data Labeling Service + where to find the data for evaluation in your BigQuery + table. When the service samples prediction input and output + from your model version and saves it to BigQuery, the data + gets stored as JSON strings in the BigQuery table. These + keys tell Data Labeling Service how to parse the JSON. + + You can provide the following entries in this field: + + - ``data_json_key``: the data key for prediction input. You + must provide either this key or ``reference_json_key``. + - ``reference_json_key``: the data reference key for + prediction input. You must provide either this key or + ``data_json_key``. + - ``label_json_key``: the label key for prediction output. + Required. + - ``label_score_json_key``: the score key for prediction + output. Required. + - ``bounding_box_json_key``: the bounding box key for + prediction output. Required if your model version perform + image object detection. + + Learn `how to configure prediction + keys `__. + example_count (int): + Required. The maximum number of predictions to sample and + save to BigQuery during each [evaluation + interval][google.cloud.datalabeling.v1beta1.EvaluationJob.schedule]. + This limit overrides ``example_sample_percentage``: even if + the service has not sampled enough predictions to fulfill + ``example_sample_perecentage`` during an interval, it stops + sampling predictions when it meets this limit. + example_sample_percentage (float): + Required. Fraction of predictions to sample and save to + BigQuery during each [evaluation + interval][google.cloud.datalabeling.v1beta1.EvaluationJob.schedule]. + For example, 0.1 means 10% of predictions served by your + model version get saved to BigQuery. + evaluation_job_alert_config (google.cloud.datalabeling_v1beta1.types.EvaluationJobAlertConfig): + Optional. Configuration details for + evaluation job alerts. Specify this field if you + want to receive email alerts if the evaluation + job finds that your predictions have low mean + average precision during a run. + """ + + image_classification_config = proto.Field( + proto.MESSAGE, + number=4, + oneof='human_annotation_request_config', + message=gcd_human_annotation_config.ImageClassificationConfig, + ) + bounding_poly_config = proto.Field( + proto.MESSAGE, + number=5, + oneof='human_annotation_request_config', + message=gcd_human_annotation_config.BoundingPolyConfig, + ) + text_classification_config = proto.Field( + proto.MESSAGE, + number=8, + oneof='human_annotation_request_config', + message=gcd_human_annotation_config.TextClassificationConfig, + ) + input_config = proto.Field( + proto.MESSAGE, + number=1, + message=dataset.InputConfig, + ) + evaluation_config = proto.Field( + proto.MESSAGE, + number=2, + message=evaluation.EvaluationConfig, + ) + human_annotation_config = proto.Field( + proto.MESSAGE, + number=3, + message=gcd_human_annotation_config.HumanAnnotationConfig, + ) + bigquery_import_keys = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + example_count = proto.Field( + proto.INT32, + number=10, + ) + example_sample_percentage = proto.Field( + proto.DOUBLE, + number=11, + ) + evaluation_job_alert_config = proto.Field( + proto.MESSAGE, + number=13, + message='EvaluationJobAlertConfig', + ) + + +class EvaluationJobAlertConfig(proto.Message): + r"""Provides details for how an evaluation job sends email alerts + based on the results of a run. + + Attributes: + email (str): + Required. An email address to send alerts to. + min_acceptable_mean_average_precision (float): + Required. A number between 0 and 1 that describes a minimum + mean average precision threshold. When the evaluation job + runs, if it calculates that your model version's predictions + from the recent interval have + [meanAveragePrecision][google.cloud.datalabeling.v1beta1.PrCurve.mean_average_precision] + below this threshold, then it sends an alert to your + specified email. + """ + + email = proto.Field( + proto.STRING, + number=1, + ) + min_acceptable_mean_average_precision = proto.Field( + proto.DOUBLE, + number=2, + ) + + +class Attempt(proto.Message): + r"""Records a failed evaluation job run. + + Attributes: + attempt_time (google.protobuf.timestamp_pb2.Timestamp): + + partial_failures (Sequence[google.rpc.status_pb2.Status]): + Details of errors that occurred. + """ + + attempt_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + partial_failures = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py new file mode 100644 index 0000000..84e04dc --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py @@ -0,0 +1,398 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'StringAggregationType', + 'HumanAnnotationConfig', + 'ImageClassificationConfig', + 'BoundingPolyConfig', + 'PolylineConfig', + 'SegmentationConfig', + 'VideoClassificationConfig', + 'ObjectDetectionConfig', + 'ObjectTrackingConfig', + 'EventConfig', + 'TextClassificationConfig', + 'SentimentConfig', + 'TextEntityExtractionConfig', + }, +) + + +class StringAggregationType(proto.Enum): + r"""""" + STRING_AGGREGATION_TYPE_UNSPECIFIED = 0 + MAJORITY_VOTE = 1 + UNANIMOUS_VOTE = 2 + NO_AGGREGATION = 3 + + +class HumanAnnotationConfig(proto.Message): + r"""Configuration for how human labeling task should be done. + + Attributes: + instruction (str): + Required. Instruction resource name. + annotated_dataset_display_name (str): + Required. A human-readable name for + AnnotatedDataset defined by users. Maximum of 64 + characters . + annotated_dataset_description (str): + Optional. A human-readable description for + AnnotatedDataset. The description can be up to + 10000 characters long. + label_group (str): + Optional. A human-readable label used to logically group + labeling tasks. This string must match the regular + expression ``[a-zA-Z\\d_-]{0,128}``. + language_code (str): + Optional. The Language of this question, as a + `BCP-47 `__. + Default value is en-US. Only need to set this when task is + language related. For example, French text classification. + replica_count (int): + Optional. Replication of questions. Each + question will be sent to up to this number of + contributors to label. Aggregated answers will + be returned. Default is set to 1. + For image related labeling, valid values are 1, + 3, 5. + question_duration (google.protobuf.duration_pb2.Duration): + Optional. Maximum duration for contributors + to answer a question. Maximum is 3600 seconds. + Default is 3600 seconds. + contributor_emails (Sequence[str]): + Optional. If you want your own labeling + contributors to manage and work on this labeling + request, you can set these contributors here. We + will give them access to the question types in + crowdcompute. Note that these emails must be + registered in crowdcompute worker UI: + https://crowd-compute.appspot.com/ + user_email_address (str): + Email of the user who started the labeling + task and should be notified by email. If empty + no notification will be sent. + """ + + instruction = proto.Field( + proto.STRING, + number=1, + ) + annotated_dataset_display_name = proto.Field( + proto.STRING, + number=2, + ) + annotated_dataset_description = proto.Field( + proto.STRING, + number=3, + ) + label_group = proto.Field( + proto.STRING, + number=4, + ) + language_code = proto.Field( + proto.STRING, + number=5, + ) + replica_count = proto.Field( + proto.INT32, + number=6, + ) + question_duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + contributor_emails = proto.RepeatedField( + proto.STRING, + number=9, + ) + user_email_address = proto.Field( + proto.STRING, + number=10, + ) + + +class ImageClassificationConfig(proto.Message): + r"""Config for image classification human labeling task. + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. + allow_multi_label (bool): + Optional. If allow_multi_label is true, contributors are + able to choose multiple labels for one image. + answer_aggregation_type (google.cloud.datalabeling_v1beta1.types.StringAggregationType): + Optional. The type of how to aggregate + answers. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + allow_multi_label = proto.Field( + proto.BOOL, + number=2, + ) + answer_aggregation_type = proto.Field( + proto.ENUM, + number=3, + enum='StringAggregationType', + ) + + +class BoundingPolyConfig(proto.Message): + r"""Config for image bounding poly (and bounding box) human + labeling task. + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. + instruction_message (str): + Optional. Instruction message showed on + contributors UI. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + instruction_message = proto.Field( + proto.STRING, + number=2, + ) + + +class PolylineConfig(proto.Message): + r"""Config for image polyline human labeling task. + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. + instruction_message (str): + Optional. Instruction message showed on + contributors UI. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + instruction_message = proto.Field( + proto.STRING, + number=2, + ) + + +class SegmentationConfig(proto.Message): + r"""Config for image segmentation + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. format: + projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} + instruction_message (str): + Instruction message showed on labelers UI. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + instruction_message = proto.Field( + proto.STRING, + number=2, + ) + + +class VideoClassificationConfig(proto.Message): + r"""Config for video classification human labeling task. + Currently two types of video classification are supported: 1. + Assign labels on the entire video. + 2. Split the video into multiple video clips based on camera + shot, and assign labels on each video clip. + + Attributes: + annotation_spec_set_configs (Sequence[google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig.AnnotationSpecSetConfig]): + Required. The list of annotation spec set + configs. Since watching a video clip takes much + longer time than an image, we support label with + multiple AnnotationSpecSet at the same time. + Labels in each AnnotationSpecSet will be shown + in a group to contributors. Contributors can + select one or more (depending on whether to + allow multi label) from each group. + apply_shot_detection (bool): + Optional. Option to apply shot detection on + the video. + """ + + class AnnotationSpecSetConfig(proto.Message): + r"""Annotation spec set with the setting of allowing multi labels + or not. + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. + allow_multi_label (bool): + Optional. If allow_multi_label is true, contributors are + able to choose multiple labels from one annotation spec set. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + allow_multi_label = proto.Field( + proto.BOOL, + number=2, + ) + + annotation_spec_set_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AnnotationSpecSetConfig, + ) + apply_shot_detection = proto.Field( + proto.BOOL, + number=2, + ) + + +class ObjectDetectionConfig(proto.Message): + r"""Config for video object detection human labeling task. + Object detection will be conducted on the images extracted from + the video, and those objects will be labeled with bounding + boxes. User need to specify the number of images to be extracted + per second as the extraction frame rate. + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. + extraction_frame_rate (float): + Required. Number of frames per second to be + extracted from the video. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + extraction_frame_rate = proto.Field( + proto.DOUBLE, + number=3, + ) + + +class ObjectTrackingConfig(proto.Message): + r"""Config for video object tracking human labeling task. + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + + +class EventConfig(proto.Message): + r"""Config for video event human labeling task. + + Attributes: + annotation_spec_sets (Sequence[str]): + Required. The list of annotation spec set + resource name. Similar to video classification, + we support selecting event from multiple + AnnotationSpecSet at the same time. + """ + + annotation_spec_sets = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class TextClassificationConfig(proto.Message): + r"""Config for text classification human labeling task. + + Attributes: + allow_multi_label (bool): + Optional. If allow_multi_label is true, contributors are + able to choose multiple labels for one text segment. + annotation_spec_set (str): + Required. Annotation spec set resource name. + sentiment_config (google.cloud.datalabeling_v1beta1.types.SentimentConfig): + Optional. Configs for sentiment selection. + """ + + allow_multi_label = proto.Field( + proto.BOOL, + number=1, + ) + annotation_spec_set = proto.Field( + proto.STRING, + number=2, + ) + sentiment_config = proto.Field( + proto.MESSAGE, + number=3, + message='SentimentConfig', + ) + + +class SentimentConfig(proto.Message): + r"""Config for setting up sentiments. + + Attributes: + enable_label_sentiment_selection (bool): + If set to true, contributors will have the + option to select sentiment of the label they + selected, to mark it as negative or positive + label. Default is false. + """ + + enable_label_sentiment_selection = proto.Field( + proto.BOOL, + number=1, + ) + + +class TextEntityExtractionConfig(proto.Message): + r"""Config for text entity extraction human labeling task. + + Attributes: + annotation_spec_set (str): + Required. Annotation spec set resource name. + """ + + annotation_spec_set = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py new file mode 100644 index 0000000..8f50b9f --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py @@ -0,0 +1,146 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.datalabeling_v1beta1.types import dataset +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'Instruction', + 'CsvInstruction', + 'PdfInstruction', + }, +) + + +class Instruction(proto.Message): + r"""Instruction of how to perform the labeling task for human + operators. Currently only PDF instruction is supported. + + Attributes: + name (str): + Output only. Instruction resource name, format: + projects/{project_id}/instructions/{instruction_id} + display_name (str): + Required. The display name of the + instruction. Maximum of 64 characters. + description (str): + Optional. User-provided description of the + instruction. The description can be up to 10000 + characters long. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time of instruction. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update time of instruction. + data_type (google.cloud.datalabeling_v1beta1.types.DataType): + Required. The data type of this instruction. + csv_instruction (google.cloud.datalabeling_v1beta1.types.CsvInstruction): + Deprecated: this instruction format is not supported any + more. Instruction from a CSV file, such as for + classification task. The CSV file should have exact two + columns, in the following format: + + - The first column is labeled data, such as an image + reference, text. + - The second column is comma separated labels associated + with data. + pdf_instruction (google.cloud.datalabeling_v1beta1.types.PdfInstruction): + Instruction from a PDF document. The PDF + should be in a Cloud Storage bucket. + blocking_resources (Sequence[str]): + Output only. The names of any related + resources that are blocking changes to the + instruction. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + data_type = proto.Field( + proto.ENUM, + number=6, + enum=dataset.DataType, + ) + csv_instruction = proto.Field( + proto.MESSAGE, + number=7, + message='CsvInstruction', + ) + pdf_instruction = proto.Field( + proto.MESSAGE, + number=9, + message='PdfInstruction', + ) + blocking_resources = proto.RepeatedField( + proto.STRING, + number=10, + ) + + +class CsvInstruction(proto.Message): + r"""Deprecated: this instruction format is not supported any + more. Instruction from a CSV file. + + Attributes: + gcs_file_uri (str): + CSV file for the instruction. Only gcs path + is allowed. + """ + + gcs_file_uri = proto.Field( + proto.STRING, + number=1, + ) + + +class PdfInstruction(proto.Message): + r"""Instruction from a PDF file. + + Attributes: + gcs_file_uri (str): + PDF file for the instruction. Only gcs path + is allowed. + """ + + gcs_file_uri = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py new file mode 100644 index 0000000..72a54b8 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py @@ -0,0 +1,549 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import human_annotation_config +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datalabeling.v1beta1', + manifest={ + 'ImportDataOperationResponse', + 'ExportDataOperationResponse', + 'ImportDataOperationMetadata', + 'ExportDataOperationMetadata', + 'LabelOperationMetadata', + 'LabelImageClassificationOperationMetadata', + 'LabelImageBoundingBoxOperationMetadata', + 'LabelImageOrientedBoundingBoxOperationMetadata', + 'LabelImageBoundingPolyOperationMetadata', + 'LabelImagePolylineOperationMetadata', + 'LabelImageSegmentationOperationMetadata', + 'LabelVideoClassificationOperationMetadata', + 'LabelVideoObjectDetectionOperationMetadata', + 'LabelVideoObjectTrackingOperationMetadata', + 'LabelVideoEventOperationMetadata', + 'LabelTextClassificationOperationMetadata', + 'LabelTextEntityExtractionOperationMetadata', + 'CreateInstructionMetadata', + }, +) + + +class ImportDataOperationResponse(proto.Message): + r"""Response used for ImportData longrunning operation. + + Attributes: + dataset (str): + Ouptut only. The name of imported dataset. + total_count (int): + Output only. Total number of examples + requested to import + import_count (int): + Output only. Number of examples imported + successfully. + """ + + dataset = proto.Field( + proto.STRING, + number=1, + ) + total_count = proto.Field( + proto.INT32, + number=2, + ) + import_count = proto.Field( + proto.INT32, + number=3, + ) + + +class ExportDataOperationResponse(proto.Message): + r"""Response used for ExportDataset longrunning operation. + + Attributes: + dataset (str): + Ouptut only. The name of dataset. "projects/*/datasets/*". + total_count (int): + Output only. Total number of examples + requested to export + export_count (int): + Output only. Number of examples exported + successfully. + label_stats (google.cloud.datalabeling_v1beta1.types.LabelStats): + Output only. Statistic infos of labels in the + exported dataset. + output_config (google.cloud.datalabeling_v1beta1.types.OutputConfig): + Output only. output_config in the ExportData request. + """ + + dataset = proto.Field( + proto.STRING, + number=1, + ) + total_count = proto.Field( + proto.INT32, + number=2, + ) + export_count = proto.Field( + proto.INT32, + number=3, + ) + label_stats = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_dataset.LabelStats, + ) + output_config = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_dataset.OutputConfig, + ) + + +class ImportDataOperationMetadata(proto.Message): + r"""Metadata of an ImportData operation. + + Attributes: + dataset (str): + Output only. The name of imported dataset. + "projects/*/datasets/*". + partial_failures (Sequence[google.rpc.status_pb2.Status]): + Output only. Partial failures encountered. + E.g. single files that couldn't be read. + Status details field will contain standard GCP + error details. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when import dataset + request was created. + """ + + dataset = proto.Field( + proto.STRING, + number=1, + ) + partial_failures = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ExportDataOperationMetadata(proto.Message): + r"""Metadata of an ExportData operation. + + Attributes: + dataset (str): + Output only. The name of dataset to be exported. + "projects/*/datasets/*". + partial_failures (Sequence[google.rpc.status_pb2.Status]): + Output only. Partial failures encountered. + E.g. single files that couldn't be read. + Status details field will contain standard GCP + error details. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when export dataset + request was created. + """ + + dataset = proto.Field( + proto.STRING, + number=1, + ) + partial_failures = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class LabelOperationMetadata(proto.Message): + r"""Metadata of a labeling operation, such as LabelImage or + LabelVideo. Next tag: 20 + + Attributes: + image_classification_details (google.cloud.datalabeling_v1beta1.types.LabelImageClassificationOperationMetadata): + Details of label image classification + operation. + image_bounding_box_details (google.cloud.datalabeling_v1beta1.types.LabelImageBoundingBoxOperationMetadata): + Details of label image bounding box + operation. + image_bounding_poly_details (google.cloud.datalabeling_v1beta1.types.LabelImageBoundingPolyOperationMetadata): + Details of label image bounding poly + operation. + image_oriented_bounding_box_details (google.cloud.datalabeling_v1beta1.types.LabelImageOrientedBoundingBoxOperationMetadata): + Details of label image oriented bounding box + operation. + image_polyline_details (google.cloud.datalabeling_v1beta1.types.LabelImagePolylineOperationMetadata): + Details of label image polyline operation. + image_segmentation_details (google.cloud.datalabeling_v1beta1.types.LabelImageSegmentationOperationMetadata): + Details of label image segmentation + operation. + video_classification_details (google.cloud.datalabeling_v1beta1.types.LabelVideoClassificationOperationMetadata): + Details of label video classification + operation. + video_object_detection_details (google.cloud.datalabeling_v1beta1.types.LabelVideoObjectDetectionOperationMetadata): + Details of label video object detection + operation. + video_object_tracking_details (google.cloud.datalabeling_v1beta1.types.LabelVideoObjectTrackingOperationMetadata): + Details of label video object tracking + operation. + video_event_details (google.cloud.datalabeling_v1beta1.types.LabelVideoEventOperationMetadata): + Details of label video event operation. + text_classification_details (google.cloud.datalabeling_v1beta1.types.LabelTextClassificationOperationMetadata): + Details of label text classification + operation. + text_entity_extraction_details (google.cloud.datalabeling_v1beta1.types.LabelTextEntityExtractionOperationMetadata): + Details of label text entity extraction + operation. + progress_percent (int): + Output only. Progress of label operation. Range: [0, 100]. + partial_failures (Sequence[google.rpc.status_pb2.Status]): + Output only. Partial failures encountered. + E.g. single files that couldn't be read. + Status details field will contain standard GCP + error details. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when labeling request + was created. + """ + + image_classification_details = proto.Field( + proto.MESSAGE, + number=3, + oneof='details', + message='LabelImageClassificationOperationMetadata', + ) + image_bounding_box_details = proto.Field( + proto.MESSAGE, + number=4, + oneof='details', + message='LabelImageBoundingBoxOperationMetadata', + ) + image_bounding_poly_details = proto.Field( + proto.MESSAGE, + number=11, + oneof='details', + message='LabelImageBoundingPolyOperationMetadata', + ) + image_oriented_bounding_box_details = proto.Field( + proto.MESSAGE, + number=14, + oneof='details', + message='LabelImageOrientedBoundingBoxOperationMetadata', + ) + image_polyline_details = proto.Field( + proto.MESSAGE, + number=12, + oneof='details', + message='LabelImagePolylineOperationMetadata', + ) + image_segmentation_details = proto.Field( + proto.MESSAGE, + number=15, + oneof='details', + message='LabelImageSegmentationOperationMetadata', + ) + video_classification_details = proto.Field( + proto.MESSAGE, + number=5, + oneof='details', + message='LabelVideoClassificationOperationMetadata', + ) + video_object_detection_details = proto.Field( + proto.MESSAGE, + number=6, + oneof='details', + message='LabelVideoObjectDetectionOperationMetadata', + ) + video_object_tracking_details = proto.Field( + proto.MESSAGE, + number=7, + oneof='details', + message='LabelVideoObjectTrackingOperationMetadata', + ) + video_event_details = proto.Field( + proto.MESSAGE, + number=8, + oneof='details', + message='LabelVideoEventOperationMetadata', + ) + text_classification_details = proto.Field( + proto.MESSAGE, + number=9, + oneof='details', + message='LabelTextClassificationOperationMetadata', + ) + text_entity_extraction_details = proto.Field( + proto.MESSAGE, + number=13, + oneof='details', + message='LabelTextEntityExtractionOperationMetadata', + ) + progress_percent = proto.Field( + proto.INT32, + number=1, + ) + partial_failures = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + create_time = proto.Field( + proto.MESSAGE, + number=16, + message=timestamp_pb2.Timestamp, + ) + + +class LabelImageClassificationOperationMetadata(proto.Message): + r"""Metadata of a LabelImageClassification operation. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelImageBoundingBoxOperationMetadata(proto.Message): + r"""Details of a LabelImageBoundingBox operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelImageOrientedBoundingBoxOperationMetadata(proto.Message): + r"""Details of a LabelImageOrientedBoundingBox operation + metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelImageBoundingPolyOperationMetadata(proto.Message): + r"""Details of LabelImageBoundingPoly operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelImagePolylineOperationMetadata(proto.Message): + r"""Details of LabelImagePolyline operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelImageSegmentationOperationMetadata(proto.Message): + r"""Details of a LabelImageSegmentation operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelVideoClassificationOperationMetadata(proto.Message): + r"""Details of a LabelVideoClassification operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelVideoObjectDetectionOperationMetadata(proto.Message): + r"""Details of a LabelVideoObjectDetection operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelVideoObjectTrackingOperationMetadata(proto.Message): + r"""Details of a LabelVideoObjectTracking operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelVideoEventOperationMetadata(proto.Message): + r"""Details of a LabelVideoEvent operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelTextClassificationOperationMetadata(proto.Message): + r"""Details of a LabelTextClassification operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class LabelTextEntityExtractionOperationMetadata(proto.Message): + r"""Details of a LabelTextEntityExtraction operation metadata. + + Attributes: + basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): + Basic human annotation config used in + labeling request. + """ + + basic_config = proto.Field( + proto.MESSAGE, + number=1, + message=human_annotation_config.HumanAnnotationConfig, + ) + + +class CreateInstructionMetadata(proto.Message): + r"""Metadata of a CreateInstruction operation. + + Attributes: + instruction (str): + The name of the created Instruction. + projects/{project_id}/instructions/{instruction_id} + partial_failures (Sequence[google.rpc.status_pb2.Status]): + Partial failures encountered. + E.g. single files that couldn't be read. + Status details field will contain standard GCP + error details. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when create instruction request was + created. + """ + + instruction = proto.Field( + proto.STRING, + number=1, + ) + partial_failures = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py new file mode 100644 index 0000000..240f3d4 --- /dev/null +++ b/owl-bot-staging/v1beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/datalabeling_v1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py new file mode 100644 index 0000000..4f2e670 --- /dev/null +++ b/owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py @@ -0,0 +1,209 @@ +#! /usr/bin/env python3 +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 datalabelingCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_annotation_spec_set': ('parent', 'annotation_spec_set', ), + 'create_dataset': ('parent', 'dataset', ), + 'create_evaluation_job': ('parent', 'job', ), + 'create_instruction': ('parent', 'instruction', ), + 'delete_annotated_dataset': ('name', ), + 'delete_annotation_spec_set': ('name', ), + 'delete_dataset': ('name', ), + 'delete_evaluation_job': ('name', ), + 'delete_instruction': ('name', ), + 'export_data': ('name', 'annotated_dataset', 'output_config', 'filter', 'user_email_address', ), + 'get_annotated_dataset': ('name', ), + 'get_annotation_spec_set': ('name', ), + 'get_data_item': ('name', ), + 'get_dataset': ('name', ), + 'get_evaluation': ('name', ), + 'get_evaluation_job': ('name', ), + 'get_example': ('name', 'filter', ), + 'get_instruction': ('name', ), + 'import_data': ('name', 'input_config', 'user_email_address', ), + 'label_image': ('parent', 'basic_config', 'feature', 'image_classification_config', 'bounding_poly_config', 'polyline_config', 'segmentation_config', ), + 'label_text': ('parent', 'basic_config', 'feature', 'text_classification_config', 'text_entity_extraction_config', ), + 'label_video': ('parent', 'basic_config', 'feature', 'video_classification_config', 'object_detection_config', 'object_tracking_config', 'event_config', ), + 'list_annotated_datasets': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_annotation_spec_sets': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_data_items': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_datasets': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_evaluation_jobs': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_examples': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_instructions': ('parent', 'filter', 'page_size', 'page_token', ), + 'pause_evaluation_job': ('name', ), + 'resume_evaluation_job': ('name', ), + 'search_evaluations': ('parent', 'filter', 'page_size', 'page_token', ), + 'search_example_comparisons': ('parent', 'page_size', 'page_token', ), + 'update_evaluation_job': ('evaluation_job', '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=datalabelingCallTransformer(), +): + """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 datalabeling 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py new file mode 100644 index 0000000..68a9f75 --- /dev/null +++ b/owl-bot-staging/v1beta1/setup.py @@ -0,0 +1,54 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-datalabeling', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py new file mode 100644 index 0000000..b7fa677 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py @@ -0,0 +1,10939 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +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_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.datalabeling_v1beta1.services.data_labeling_service import DataLabelingServiceAsyncClient +from google.cloud.datalabeling_v1beta1.services.data_labeling_service import DataLabelingServiceClient +from google.cloud.datalabeling_v1beta1.services.data_labeling_service import pagers +from google.cloud.datalabeling_v1beta1.services.data_labeling_service import transports +from google.cloud.datalabeling_v1beta1.services.data_labeling_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.datalabeling_v1beta1.types import annotation +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set +from google.cloud.datalabeling_v1beta1.types import data_labeling_service +from google.cloud.datalabeling_v1beta1.types import data_payloads +from google.cloud.datalabeling_v1beta1.types import dataset +from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset +from google.cloud.datalabeling_v1beta1.types import evaluation +from google.cloud.datalabeling_v1beta1.types import evaluation_job +from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job +from google.cloud.datalabeling_v1beta1.types import human_annotation_config +from google.cloud.datalabeling_v1beta1.types import instruction +from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction +from google.cloud.datalabeling_v1beta1.types import operations +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataLabelingServiceClient._get_default_mtls_endpoint(None) is None + assert DataLabelingServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataLabelingServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataLabelingServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataLabelingServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataLabelingServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DataLabelingServiceClient, + DataLabelingServiceAsyncClient, +]) +def test_data_labeling_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'datalabeling.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataLabelingServiceGrpcTransport, "grpc"), + (transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_labeling_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", [ + DataLabelingServiceClient, + DataLabelingServiceAsyncClient, +]) +def test_data_labeling_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'datalabeling.googleapis.com:443' + + +def test_data_labeling_service_client_get_transport_class(): + transport = DataLabelingServiceClient.get_transport_class() + available_transports = [ + transports.DataLabelingServiceGrpcTransport, + ] + assert transport in available_transports + + transport = DataLabelingServiceClient.get_transport_class("grpc") + assert transport == transports.DataLabelingServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc"), + (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DataLabelingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceClient)) +@mock.patch.object(DataLabelingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceAsyncClient)) +def test_data_labeling_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(DataLabelingServiceClient, '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(DataLabelingServiceClient, '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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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() + 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc", "true"), + (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc", "false"), + (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DataLabelingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceClient)) +@mock.patch.object(DataLabelingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_labeling_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc"), + (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_labeling_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc"), + (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_labeling_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_data_labeling_service_client_client_options_from_dict(): + with mock.patch('google.cloud.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataLabelingServiceClient( + 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, + ) + + +def test_create_dataset(transport: str = 'grpc', request_type=data_labeling_service.CreateDatasetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + data_item_count=1584, + ) + response = client.create_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] == data_labeling_service.CreateDatasetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + assert response.data_item_count == 1584 + + +def test_create_dataset_from_dict(): + test_create_dataset(request_type=dict) + + +def test_create_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 = DataLabelingServiceClient( + 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_dataset), + '__call__') as call: + client.create_dataset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateDatasetRequest() + + +@pytest.mark.asyncio +async def test_create_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateDatasetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + data_item_count=1584, + )) + response = await client.create_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateDatasetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + assert response.data_item_count == 1584 + + +@pytest.mark.asyncio +async def test_create_dataset_async_from_dict(): + await test_create_dataset_async(request_type=dict) + + +def test_create_dataset_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateDatasetRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + call.return_value = gcd_dataset.Dataset() + client.create_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', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_dataset_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateDatasetRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_dataset.Dataset()) + await client.create_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', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_dataset_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_dataset.Dataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_dataset( + parent='parent_value', + dataset=gcd_dataset.Dataset(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] + assert args[0].parent == 'parent_value' + assert args[0].dataset == gcd_dataset.Dataset(name='name_value') + + +def test_create_dataset_flattened_error(): + client = DataLabelingServiceClient( + 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_dataset( + data_labeling_service.CreateDatasetRequest(), + parent='parent_value', + dataset=gcd_dataset.Dataset(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_dataset_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_dataset.Dataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_dataset.Dataset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_dataset( + parent='parent_value', + dataset=gcd_dataset.Dataset(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] + assert args[0].parent == 'parent_value' + assert args[0].dataset == gcd_dataset.Dataset(name='name_value') + + +@pytest.mark.asyncio +async def test_create_dataset_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_dataset( + data_labeling_service.CreateDatasetRequest(), + parent='parent_value', + dataset=gcd_dataset.Dataset(name='name_value'), + ) + + +def test_get_dataset(transport: str = 'grpc', request_type=data_labeling_service.GetDatasetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + data_item_count=1584, + ) + response = client.get_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] == data_labeling_service.GetDatasetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + assert response.data_item_count == 1584 + + +def test_get_dataset_from_dict(): + test_get_dataset(request_type=dict) + + +def test_get_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 = DataLabelingServiceClient( + 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), + '__call__') as call: + client.get_dataset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetDatasetRequest() + + +@pytest.mark.asyncio +async def test_get_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetDatasetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + data_item_count=1584, + )) + response = await client.get_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetDatasetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + assert response.data_item_count == 1584 + + +@pytest.mark.asyncio +async def test_get_dataset_async_from_dict(): + await test_get_dataset_async(request_type=dict) + + +def test_get_dataset_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetDatasetRequest() + + 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), + '__call__') as call: + call.return_value = dataset.Dataset() + client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_dataset_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetDatasetRequest() + + 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), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) + await client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_dataset_flattened(): + client = DataLabelingServiceClient( + 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), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Dataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_dataset( + 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] + assert args[0].name == 'name_value' + + +def test_get_dataset_flattened_error(): + client = DataLabelingServiceClient( + 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( + data_labeling_service.GetDatasetRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_dataset_flattened_async(): + client = DataLabelingServiceAsyncClient( + 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), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Dataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_dataset( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_dataset_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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( + data_labeling_service.GetDatasetRequest(), + name='name_value', + ) + + +def test_list_datasets(transport: str = 'grpc', request_type=data_labeling_service.ListDatasetsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListDatasetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListDatasetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatasetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_datasets_from_dict(): + test_list_datasets(request_type=dict) + + +def test_list_datasets_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 = DataLabelingServiceClient( + 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_datasets), + '__call__') as call: + client.list_datasets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListDatasetsRequest() + + +@pytest.mark.asyncio +async def test_list_datasets_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListDatasetsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDatasetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListDatasetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatasetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_datasets_async_from_dict(): + await test_list_datasets_async(request_type=dict) + + +def test_list_datasets_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListDatasetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + call.return_value = data_labeling_service.ListDatasetsResponse() + client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_datasets_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListDatasetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDatasetsResponse()) + await client.list_datasets(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_datasets_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListDatasetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_datasets( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_datasets_flattened_error(): + client = DataLabelingServiceClient( + 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_datasets( + data_labeling_service.ListDatasetsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_datasets_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListDatasetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDatasetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_datasets( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_datasets_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_datasets( + data_labeling_service.ListDatasetsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_datasets_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_datasets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, dataset.Dataset) + for i in results) + +def test_list_datasets_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_datasets(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_datasets_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_datasets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dataset.Dataset) + for i in responses) + +@pytest.mark.asyncio +async def test_list_datasets_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_datasets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_dataset(transport: str = 'grpc', request_type=data_labeling_service.DeleteDatasetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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] == data_labeling_service.DeleteDatasetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_dataset_from_dict(): + test_delete_dataset(request_type=dict) + + +def test_delete_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 = DataLabelingServiceClient( + 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_dataset), + '__call__') as call: + client.delete_dataset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteDatasetRequest() + + +@pytest.mark.asyncio +async def test_delete_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteDatasetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteDatasetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_dataset_async_from_dict(): + await test_delete_dataset_async(request_type=dict) + + +def test_delete_dataset_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteDatasetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + call.return_value = None + client.delete_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_dataset_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteDatasetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_dataset_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_dataset( + 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] + assert args[0].name == 'name_value' + + +def test_delete_dataset_flattened_error(): + client = DataLabelingServiceClient( + 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_dataset( + data_labeling_service.DeleteDatasetRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_dataset_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_dataset( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_dataset_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_dataset( + data_labeling_service.DeleteDatasetRequest(), + name='name_value', + ) + + +def test_import_data(transport: str = 'grpc', request_type=data_labeling_service.ImportDataRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ImportDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_data_from_dict(): + test_import_data(request_type=dict) + + +def test_import_data_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 = DataLabelingServiceClient( + 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_data), + '__call__') as call: + client.import_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ImportDataRequest() + + +@pytest.mark.asyncio +async def test_import_data_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ImportDataRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data), + '__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_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ImportDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_data_async_from_dict(): + await test_import_data_async(request_type=dict) + + +def test_import_data_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ImportDataRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_import_data_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ImportDataRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_data(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_import_data_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_data), + '__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_data( + name='name_value', + input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_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] + assert args[0].name == 'name_value' + assert args[0].input_config == dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')) + + +def test_import_data_flattened_error(): + client = DataLabelingServiceClient( + 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_data( + data_labeling_service.ImportDataRequest(), + name='name_value', + input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')), + ) + + +@pytest.mark.asyncio +async def test_import_data_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_data), + '__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_data( + name='name_value', + input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].input_config == dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')) + + +@pytest.mark.asyncio +async def test_import_data_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_data( + data_labeling_service.ImportDataRequest(), + name='name_value', + input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')), + ) + + +def test_export_data(transport: str = 'grpc', request_type=data_labeling_service.ExportDataRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ExportDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_data_from_dict(): + test_export_data(request_type=dict) + + +def test_export_data_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 = DataLabelingServiceClient( + 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.export_data), + '__call__') as call: + client.export_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ExportDataRequest() + + +@pytest.mark.asyncio +async def test_export_data_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ExportDataRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_data), + '__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.export_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ExportDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_data_async_from_dict(): + await test_export_data_async(request_type=dict) + + +def test_export_data_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ExportDataRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_export_data_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ExportDataRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_data(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_export_data_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_data), + '__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.export_data( + name='name_value', + annotated_dataset='annotated_dataset_value', + filter='filter_value', + output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_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] + assert args[0].name == 'name_value' + assert args[0].annotated_dataset == 'annotated_dataset_value' + assert args[0].filter == 'filter_value' + assert args[0].output_config == dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')) + + +def test_export_data_flattened_error(): + client = DataLabelingServiceClient( + 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.export_data( + data_labeling_service.ExportDataRequest(), + name='name_value', + annotated_dataset='annotated_dataset_value', + filter='filter_value', + output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')), + ) + + +@pytest.mark.asyncio +async def test_export_data_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_data), + '__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.export_data( + name='name_value', + annotated_dataset='annotated_dataset_value', + filter='filter_value', + output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].annotated_dataset == 'annotated_dataset_value' + assert args[0].filter == 'filter_value' + assert args[0].output_config == dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')) + + +@pytest.mark.asyncio +async def test_export_data_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.export_data( + data_labeling_service.ExportDataRequest(), + name='name_value', + annotated_dataset='annotated_dataset_value', + filter='filter_value', + output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')), + ) + + +def test_get_data_item(transport: str = 'grpc', request_type=data_labeling_service.GetDataItemRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.DataItem( + name='name_value', + image_payload=data_payloads.ImagePayload(mime_type='mime_type_value'), + ) + response = client.get_data_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetDataItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.DataItem) + assert response.name == 'name_value' + + +def test_get_data_item_from_dict(): + test_get_data_item(request_type=dict) + + +def test_get_data_item_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 = DataLabelingServiceClient( + 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_data_item), + '__call__') as call: + client.get_data_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetDataItemRequest() + + +@pytest.mark.asyncio +async def test_get_data_item_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetDataItemRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.DataItem( + name='name_value', + )) + response = await client.get_data_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetDataItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.DataItem) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_data_item_async_from_dict(): + await test_get_data_item_async(request_type=dict) + + +def test_get_data_item_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetDataItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_item), + '__call__') as call: + call.return_value = dataset.DataItem() + client.get_data_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_data_item_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetDataItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DataItem()) + await client.get_data_item(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_data_item_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.DataItem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_item( + 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] + assert args[0].name == 'name_value' + + +def test_get_data_item_flattened_error(): + client = DataLabelingServiceClient( + 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_data_item( + data_labeling_service.GetDataItemRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_data_item_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.DataItem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DataItem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_item( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_data_item_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_data_item( + data_labeling_service.GetDataItemRequest(), + name='name_value', + ) + + +def test_list_data_items(transport: str = 'grpc', request_type=data_labeling_service.ListDataItemsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListDataItemsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListDataItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataItemsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_items_from_dict(): + test_list_data_items(request_type=dict) + + +def test_list_data_items_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 = DataLabelingServiceClient( + 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_data_items), + '__call__') as call: + client.list_data_items() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListDataItemsRequest() + + +@pytest.mark.asyncio +async def test_list_data_items_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListDataItemsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDataItemsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListDataItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataItemsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_items_async_from_dict(): + await test_list_data_items_async(request_type=dict) + + +def test_list_data_items_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListDataItemsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__') as call: + call.return_value = data_labeling_service.ListDataItemsResponse() + client.list_data_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_data_items_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListDataItemsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDataItemsResponse()) + await client.list_data_items(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_data_items_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListDataItemsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_items( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_data_items_flattened_error(): + client = DataLabelingServiceClient( + 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_data_items( + data_labeling_service.ListDataItemsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_data_items_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListDataItemsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDataItemsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_items( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_data_items_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_data_items( + data_labeling_service.ListDataItemsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_data_items_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + dataset.DataItem(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[], + next_page_token='def', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_items(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, dataset.DataItem) + for i in results) + +def test_list_data_items_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + dataset.DataItem(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[], + next_page_token='def', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_items(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_data_items_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + dataset.DataItem(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[], + next_page_token='def', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_items(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dataset.DataItem) + for i in responses) + +@pytest.mark.asyncio +async def test_list_data_items_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + dataset.DataItem(), + ], + next_page_token='abc', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[], + next_page_token='def', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListDataItemsResponse( + data_items=[ + dataset.DataItem(), + dataset.DataItem(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_data_items(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_annotated_dataset(transport: str = 'grpc', request_type=data_labeling_service.GetAnnotatedDatasetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotated_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.AnnotatedDataset( + name='name_value', + display_name='display_name_value', + description='description_value', + annotation_source=annotation.AnnotationSource.OPERATOR, + annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, + example_count=1396, + completed_example_count=2448, + blocking_resources=['blocking_resources_value'], + ) + response = client.get_annotated_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] == data_labeling_service.GetAnnotatedDatasetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.AnnotatedDataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.annotation_source == annotation.AnnotationSource.OPERATOR + assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION + assert response.example_count == 1396 + assert response.completed_example_count == 2448 + assert response.blocking_resources == ['blocking_resources_value'] + + +def test_get_annotated_dataset_from_dict(): + test_get_annotated_dataset(request_type=dict) + + +def test_get_annotated_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 = DataLabelingServiceClient( + 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_annotated_dataset), + '__call__') as call: + client.get_annotated_dataset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetAnnotatedDatasetRequest() + + +@pytest.mark.asyncio +async def test_get_annotated_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetAnnotatedDatasetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotated_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.AnnotatedDataset( + name='name_value', + display_name='display_name_value', + description='description_value', + annotation_source=annotation.AnnotationSource.OPERATOR, + annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, + example_count=1396, + completed_example_count=2448, + blocking_resources=['blocking_resources_value'], + )) + response = await client.get_annotated_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetAnnotatedDatasetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.AnnotatedDataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.annotation_source == annotation.AnnotationSource.OPERATOR + assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION + assert response.example_count == 1396 + assert response.completed_example_count == 2448 + assert response.blocking_resources == ['blocking_resources_value'] + + +@pytest.mark.asyncio +async def test_get_annotated_dataset_async_from_dict(): + await test_get_annotated_dataset_async(request_type=dict) + + +def test_get_annotated_dataset_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetAnnotatedDatasetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotated_dataset), + '__call__') as call: + call.return_value = dataset.AnnotatedDataset() + client.get_annotated_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_annotated_dataset_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetAnnotatedDatasetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotated_dataset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.AnnotatedDataset()) + await client.get_annotated_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_annotated_dataset_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotated_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.AnnotatedDataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_annotated_dataset( + 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] + assert args[0].name == 'name_value' + + +def test_get_annotated_dataset_flattened_error(): + client = DataLabelingServiceClient( + 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_annotated_dataset( + data_labeling_service.GetAnnotatedDatasetRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_annotated_dataset_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotated_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.AnnotatedDataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.AnnotatedDataset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_annotated_dataset( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_annotated_dataset_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_annotated_dataset( + data_labeling_service.GetAnnotatedDatasetRequest(), + name='name_value', + ) + + +def test_list_annotated_datasets(transport: str = 'grpc', request_type=data_labeling_service.ListAnnotatedDatasetsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotated_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_annotated_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListAnnotatedDatasetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotatedDatasetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_annotated_datasets_from_dict(): + test_list_annotated_datasets(request_type=dict) + + +def test_list_annotated_datasets_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 = DataLabelingServiceClient( + 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_annotated_datasets), + '__call__') as call: + client.list_annotated_datasets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListAnnotatedDatasetsRequest() + + +@pytest.mark.asyncio +async def test_list_annotated_datasets_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListAnnotatedDatasetsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotated_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotatedDatasetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_annotated_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListAnnotatedDatasetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotatedDatasetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_annotated_datasets_async_from_dict(): + await test_list_annotated_datasets_async(request_type=dict) + + +def test_list_annotated_datasets_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListAnnotatedDatasetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__') as call: + call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse() + client.list_annotated_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_annotated_datasets_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListAnnotatedDatasetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotatedDatasetsResponse()) + await client.list_annotated_datasets(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_annotated_datasets_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_annotated_datasets( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_annotated_datasets_flattened_error(): + client = DataLabelingServiceClient( + 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_annotated_datasets( + data_labeling_service.ListAnnotatedDatasetsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_annotated_datasets_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotatedDatasetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_annotated_datasets( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_annotated_datasets_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_annotated_datasets( + data_labeling_service.ListAnnotatedDatasetsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_annotated_datasets_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_annotated_datasets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, dataset.AnnotatedDataset) + for i in results) + +def test_list_annotated_datasets_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_annotated_datasets(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_annotated_datasets_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_annotated_datasets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dataset.AnnotatedDataset) + for i in responses) + +@pytest.mark.asyncio +async def test_list_annotated_datasets_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotated_datasets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotatedDatasetsResponse( + annotated_datasets=[ + dataset.AnnotatedDataset(), + dataset.AnnotatedDataset(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_annotated_datasets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_annotated_dataset(transport: str = 'grpc', request_type=data_labeling_service.DeleteAnnotatedDatasetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotated_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_annotated_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] == data_labeling_service.DeleteAnnotatedDatasetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_annotated_dataset_from_dict(): + test_delete_annotated_dataset(request_type=dict) + + +def test_delete_annotated_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 = DataLabelingServiceClient( + 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_annotated_dataset), + '__call__') as call: + client.delete_annotated_dataset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteAnnotatedDatasetRequest() + + +@pytest.mark.asyncio +async def test_delete_annotated_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteAnnotatedDatasetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotated_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_annotated_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteAnnotatedDatasetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_annotated_dataset_async_from_dict(): + await test_delete_annotated_dataset_async(request_type=dict) + + +def test_delete_annotated_dataset_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteAnnotatedDatasetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotated_dataset), + '__call__') as call: + call.return_value = None + client.delete_annotated_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_annotated_dataset_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteAnnotatedDatasetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotated_dataset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_annotated_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_label_image(transport: str = 'grpc', request_type=data_labeling_service.LabelImageRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_image), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.label_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_label_image_from_dict(): + test_label_image(request_type=dict) + + +def test_label_image_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 = DataLabelingServiceClient( + 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.label_image), + '__call__') as call: + client.label_image() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelImageRequest() + + +@pytest.mark.asyncio +async def test_label_image_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.LabelImageRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_image), + '__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.label_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_label_image_async_from_dict(): + await test_label_image_async(request_type=dict) + + +def test_label_image_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.LabelImageRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_image), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.label_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_label_image_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.LabelImageRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_image), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.label_image(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_label_image_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_image), + '__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.label_image( + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') + assert args[0].feature == data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION + + +def test_label_image_flattened_error(): + client = DataLabelingServiceClient( + 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.label_image( + data_labeling_service.LabelImageRequest(), + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, + ) + + +@pytest.mark.asyncio +async def test_label_image_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_image), + '__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.label_image( + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') + assert args[0].feature == data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION + + +@pytest.mark.asyncio +async def test_label_image_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.label_image( + data_labeling_service.LabelImageRequest(), + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, + ) + + +def test_label_video(transport: str = 'grpc', request_type=data_labeling_service.LabelVideoRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.label_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_label_video_from_dict(): + test_label_video(request_type=dict) + + +def test_label_video_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 = DataLabelingServiceClient( + 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.label_video), + '__call__') as call: + client.label_video() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelVideoRequest() + + +@pytest.mark.asyncio +async def test_label_video_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.LabelVideoRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_video), + '__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.label_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_label_video_async_from_dict(): + await test_label_video_async(request_type=dict) + + +def test_label_video_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.LabelVideoRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_video), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.label_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_label_video_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.LabelVideoRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_video), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.label_video(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_label_video_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_video), + '__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.label_video( + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') + assert args[0].feature == data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION + + +def test_label_video_flattened_error(): + client = DataLabelingServiceClient( + 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.label_video( + data_labeling_service.LabelVideoRequest(), + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, + ) + + +@pytest.mark.asyncio +async def test_label_video_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_video), + '__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.label_video( + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') + assert args[0].feature == data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION + + +@pytest.mark.asyncio +async def test_label_video_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.label_video( + data_labeling_service.LabelVideoRequest(), + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, + ) + + +def test_label_text(transport: str = 'grpc', request_type=data_labeling_service.LabelTextRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_text), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.label_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_label_text_from_dict(): + test_label_text(request_type=dict) + + +def test_label_text_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 = DataLabelingServiceClient( + 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.label_text), + '__call__') as call: + client.label_text() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelTextRequest() + + +@pytest.mark.asyncio +async def test_label_text_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.LabelTextRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_text), + '__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.label_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.LabelTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_label_text_async_from_dict(): + await test_label_text_async(request_type=dict) + + +def test_label_text_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.LabelTextRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_text), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.label_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_label_text_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.LabelTextRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_text), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.label_text(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_label_text_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_text), + '__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.label_text( + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') + assert args[0].feature == data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION + + +def test_label_text_flattened_error(): + client = DataLabelingServiceClient( + 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.label_text( + data_labeling_service.LabelTextRequest(), + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, + ) + + +@pytest.mark.asyncio +async def test_label_text_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.label_text), + '__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.label_text( + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') + assert args[0].feature == data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION + + +@pytest.mark.asyncio +async def test_label_text_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.label_text( + data_labeling_service.LabelTextRequest(), + parent='parent_value', + basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), + feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, + ) + + +def test_get_example(transport: str = 'grpc', request_type=data_labeling_service.GetExampleRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Example( + name='name_value', + image_payload=data_payloads.ImagePayload(mime_type='mime_type_value'), + ) + response = client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetExampleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.Example) + assert response.name == 'name_value' + + +def test_get_example_from_dict(): + test_get_example(request_type=dict) + + +def test_get_example_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 = DataLabelingServiceClient( + 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_example), + '__call__') as call: + client.get_example() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetExampleRequest() + + +@pytest.mark.asyncio +async def test_get_example_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetExampleRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.Example( + name='name_value', + )) + response = await client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetExampleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.Example) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_example_async_from_dict(): + await test_get_example_async(request_type=dict) + + +def test_get_example_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetExampleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_example), + '__call__') as call: + call.return_value = dataset.Example() + client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_example_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetExampleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_example), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Example()) + await client.get_example(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_example_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_example), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Example() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_example( + name='name_value', + filter='filter_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] + assert args[0].name == 'name_value' + assert args[0].filter == 'filter_value' + + +def test_get_example_flattened_error(): + client = DataLabelingServiceClient( + 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_example( + data_labeling_service.GetExampleRequest(), + name='name_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_get_example_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_example), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Example() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Example()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_example( + name='name_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_get_example_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_example( + data_labeling_service.GetExampleRequest(), + name='name_value', + filter='filter_value', + ) + + +def test_list_examples(transport: str = 'grpc', request_type=data_labeling_service.ListExamplesRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_examples), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListExamplesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListExamplesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_examples_from_dict(): + test_list_examples(request_type=dict) + + +def test_list_examples_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 = DataLabelingServiceClient( + 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_examples), + '__call__') as call: + client.list_examples() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListExamplesRequest() + + +@pytest.mark.asyncio +async def test_list_examples_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListExamplesRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_examples), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListExamplesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListExamplesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_examples_async_from_dict(): + await test_list_examples_async(request_type=dict) + + +def test_list_examples_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListExamplesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__') as call: + call.return_value = data_labeling_service.ListExamplesResponse() + client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_examples_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListExamplesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListExamplesResponse()) + await client.list_examples(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_examples_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListExamplesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_examples( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_examples_flattened_error(): + client = DataLabelingServiceClient( + 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_examples( + data_labeling_service.ListExamplesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_examples_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListExamplesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListExamplesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_examples( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_examples_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_examples( + data_labeling_service.ListExamplesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_examples_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + dataset.Example(), + ], + next_page_token='abc', + ), + data_labeling_service.ListExamplesResponse( + examples=[], + next_page_token='def', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_examples(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, dataset.Example) + for i in results) + +def test_list_examples_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + dataset.Example(), + ], + next_page_token='abc', + ), + data_labeling_service.ListExamplesResponse( + examples=[], + next_page_token='def', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + ], + ), + RuntimeError, + ) + pages = list(client.list_examples(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_examples_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + dataset.Example(), + ], + next_page_token='abc', + ), + data_labeling_service.ListExamplesResponse( + examples=[], + next_page_token='def', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_examples(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dataset.Example) + for i in responses) + +@pytest.mark.asyncio +async def test_list_examples_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + dataset.Example(), + ], + next_page_token='abc', + ), + data_labeling_service.ListExamplesResponse( + examples=[], + next_page_token='def', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListExamplesResponse( + examples=[ + dataset.Example(), + dataset.Example(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_examples(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_create_annotation_spec_set(transport: str = 'grpc', request_type=data_labeling_service.CreateAnnotationSpecSetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_annotation_spec_set.AnnotationSpecSet( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + ) + response = client.create_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateAnnotationSpecSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_annotation_spec_set.AnnotationSpecSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + + +def test_create_annotation_spec_set_from_dict(): + test_create_annotation_spec_set(request_type=dict) + + +def test_create_annotation_spec_set_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 = DataLabelingServiceClient( + 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_annotation_spec_set), + '__call__') as call: + client.create_annotation_spec_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateAnnotationSpecSetRequest() + + +@pytest.mark.asyncio +async def test_create_annotation_spec_set_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateAnnotationSpecSetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_annotation_spec_set.AnnotationSpecSet( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + )) + response = await client.create_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateAnnotationSpecSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_annotation_spec_set.AnnotationSpecSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + + +@pytest.mark.asyncio +async def test_create_annotation_spec_set_async_from_dict(): + await test_create_annotation_spec_set_async(request_type=dict) + + +def test_create_annotation_spec_set_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateAnnotationSpecSetRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation_spec_set), + '__call__') as call: + call.return_value = gcd_annotation_spec_set.AnnotationSpecSet() + client.create_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_annotation_spec_set_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateAnnotationSpecSetRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation_spec_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_annotation_spec_set.AnnotationSpecSet()) + await client.create_annotation_spec_set(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_annotation_spec_set_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_annotation_spec_set.AnnotationSpecSet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_annotation_spec_set( + parent='parent_value', + annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(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] + assert args[0].parent == 'parent_value' + assert args[0].annotation_spec_set == gcd_annotation_spec_set.AnnotationSpecSet(name='name_value') + + +def test_create_annotation_spec_set_flattened_error(): + client = DataLabelingServiceClient( + 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_annotation_spec_set( + data_labeling_service.CreateAnnotationSpecSetRequest(), + parent='parent_value', + annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_annotation_spec_set_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_annotation_spec_set.AnnotationSpecSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_annotation_spec_set.AnnotationSpecSet()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_annotation_spec_set( + parent='parent_value', + annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(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] + assert args[0].parent == 'parent_value' + assert args[0].annotation_spec_set == gcd_annotation_spec_set.AnnotationSpecSet(name='name_value') + + +@pytest.mark.asyncio +async def test_create_annotation_spec_set_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_annotation_spec_set( + data_labeling_service.CreateAnnotationSpecSetRequest(), + parent='parent_value', + annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(name='name_value'), + ) + + +def test_get_annotation_spec_set(transport: str = 'grpc', request_type=data_labeling_service.GetAnnotationSpecSetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = annotation_spec_set.AnnotationSpecSet( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + ) + response = client.get_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetAnnotationSpecSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, annotation_spec_set.AnnotationSpecSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + + +def test_get_annotation_spec_set_from_dict(): + test_get_annotation_spec_set(request_type=dict) + + +def test_get_annotation_spec_set_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 = DataLabelingServiceClient( + 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_annotation_spec_set), + '__call__') as call: + client.get_annotation_spec_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetAnnotationSpecSetRequest() + + +@pytest.mark.asyncio +async def test_get_annotation_spec_set_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetAnnotationSpecSetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(annotation_spec_set.AnnotationSpecSet( + name='name_value', + display_name='display_name_value', + description='description_value', + blocking_resources=['blocking_resources_value'], + )) + response = await client.get_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetAnnotationSpecSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, annotation_spec_set.AnnotationSpecSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.blocking_resources == ['blocking_resources_value'] + + +@pytest.mark.asyncio +async def test_get_annotation_spec_set_async_from_dict(): + await test_get_annotation_spec_set_async(request_type=dict) + + +def test_get_annotation_spec_set_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetAnnotationSpecSetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation_spec_set), + '__call__') as call: + call.return_value = annotation_spec_set.AnnotationSpecSet() + client.get_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_annotation_spec_set_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetAnnotationSpecSetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation_spec_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(annotation_spec_set.AnnotationSpecSet()) + await client.get_annotation_spec_set(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_annotation_spec_set_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = annotation_spec_set.AnnotationSpecSet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_annotation_spec_set( + 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] + assert args[0].name == 'name_value' + + +def test_get_annotation_spec_set_flattened_error(): + client = DataLabelingServiceClient( + 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_annotation_spec_set( + data_labeling_service.GetAnnotationSpecSetRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_annotation_spec_set_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = annotation_spec_set.AnnotationSpecSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(annotation_spec_set.AnnotationSpecSet()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_annotation_spec_set( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_annotation_spec_set_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_annotation_spec_set( + data_labeling_service.GetAnnotationSpecSetRequest(), + name='name_value', + ) + + +def test_list_annotation_spec_sets(transport: str = 'grpc', request_type=data_labeling_service.ListAnnotationSpecSetsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_annotation_spec_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListAnnotationSpecSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationSpecSetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_annotation_spec_sets_from_dict(): + test_list_annotation_spec_sets(request_type=dict) + + +def test_list_annotation_spec_sets_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 = DataLabelingServiceClient( + 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_annotation_spec_sets), + '__call__') as call: + client.list_annotation_spec_sets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListAnnotationSpecSetsRequest() + + +@pytest.mark.asyncio +async def test_list_annotation_spec_sets_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListAnnotationSpecSetsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotationSpecSetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_annotation_spec_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListAnnotationSpecSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationSpecSetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_annotation_spec_sets_async_from_dict(): + await test_list_annotation_spec_sets_async(request_type=dict) + + +def test_list_annotation_spec_sets_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListAnnotationSpecSetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__') as call: + call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse() + client.list_annotation_spec_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_annotation_spec_sets_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListAnnotationSpecSetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotationSpecSetsResponse()) + await client.list_annotation_spec_sets(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_annotation_spec_sets_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_annotation_spec_sets( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_annotation_spec_sets_flattened_error(): + client = DataLabelingServiceClient( + 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_annotation_spec_sets( + data_labeling_service.ListAnnotationSpecSetsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_annotation_spec_sets_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotationSpecSetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_annotation_spec_sets( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_annotation_spec_sets_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_annotation_spec_sets( + data_labeling_service.ListAnnotationSpecSetsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_annotation_spec_sets_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_annotation_spec_sets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, annotation_spec_set.AnnotationSpecSet) + for i in results) + +def test_list_annotation_spec_sets_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_annotation_spec_sets(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_annotation_spec_sets_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_annotation_spec_sets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, annotation_spec_set.AnnotationSpecSet) + for i in responses) + +@pytest.mark.asyncio +async def test_list_annotation_spec_sets_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotation_spec_sets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='abc', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[], + next_page_token='def', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListAnnotationSpecSetsResponse( + annotation_spec_sets=[ + annotation_spec_set.AnnotationSpecSet(), + annotation_spec_set.AnnotationSpecSet(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_annotation_spec_sets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_annotation_spec_set(transport: str = 'grpc', request_type=data_labeling_service.DeleteAnnotationSpecSetRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteAnnotationSpecSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_annotation_spec_set_from_dict(): + test_delete_annotation_spec_set(request_type=dict) + + +def test_delete_annotation_spec_set_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 = DataLabelingServiceClient( + 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_annotation_spec_set), + '__call__') as call: + client.delete_annotation_spec_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteAnnotationSpecSetRequest() + + +@pytest.mark.asyncio +async def test_delete_annotation_spec_set_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteAnnotationSpecSetRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteAnnotationSpecSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_annotation_spec_set_async_from_dict(): + await test_delete_annotation_spec_set_async(request_type=dict) + + +def test_delete_annotation_spec_set_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteAnnotationSpecSetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation_spec_set), + '__call__') as call: + call.return_value = None + client.delete_annotation_spec_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_annotation_spec_set_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteAnnotationSpecSetRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation_spec_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_annotation_spec_set(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_annotation_spec_set_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_annotation_spec_set( + 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] + assert args[0].name == 'name_value' + + +def test_delete_annotation_spec_set_flattened_error(): + client = DataLabelingServiceClient( + 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_annotation_spec_set( + data_labeling_service.DeleteAnnotationSpecSetRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_annotation_spec_set_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation_spec_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_annotation_spec_set( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_annotation_spec_set_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_annotation_spec_set( + data_labeling_service.DeleteAnnotationSpecSetRequest(), + name='name_value', + ) + + +def test_create_instruction(transport: str = 'grpc', request_type=data_labeling_service.CreateInstructionRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateInstructionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instruction_from_dict(): + test_create_instruction(request_type=dict) + + +def test_create_instruction_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 = DataLabelingServiceClient( + 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_instruction), + '__call__') as call: + client.create_instruction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateInstructionRequest() + + +@pytest.mark.asyncio +async def test_create_instruction_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateInstructionRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instruction), + '__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.create_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateInstructionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instruction_async_from_dict(): + await test_create_instruction_async(request_type=dict) + + +def test_create_instruction_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateInstructionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instruction), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instruction_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateInstructionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instruction), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_instruction(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_instruction_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instruction), + '__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.create_instruction( + parent='parent_value', + instruction=gcd_instruction.Instruction(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] + assert args[0].parent == 'parent_value' + assert args[0].instruction == gcd_instruction.Instruction(name='name_value') + + +def test_create_instruction_flattened_error(): + client = DataLabelingServiceClient( + 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_instruction( + data_labeling_service.CreateInstructionRequest(), + parent='parent_value', + instruction=gcd_instruction.Instruction(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_instruction_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instruction), + '__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.create_instruction( + parent='parent_value', + instruction=gcd_instruction.Instruction(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] + assert args[0].parent == 'parent_value' + assert args[0].instruction == gcd_instruction.Instruction(name='name_value') + + +@pytest.mark.asyncio +async def test_create_instruction_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_instruction( + data_labeling_service.CreateInstructionRequest(), + parent='parent_value', + instruction=gcd_instruction.Instruction(name='name_value'), + ) + + +def test_get_instruction(transport: str = 'grpc', request_type=data_labeling_service.GetInstructionRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instruction.Instruction( + name='name_value', + display_name='display_name_value', + description='description_value', + data_type=dataset.DataType.IMAGE, + blocking_resources=['blocking_resources_value'], + ) + response = client.get_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetInstructionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, instruction.Instruction) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.data_type == dataset.DataType.IMAGE + assert response.blocking_resources == ['blocking_resources_value'] + + +def test_get_instruction_from_dict(): + test_get_instruction(request_type=dict) + + +def test_get_instruction_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 = DataLabelingServiceClient( + 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_instruction), + '__call__') as call: + client.get_instruction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetInstructionRequest() + + +@pytest.mark.asyncio +async def test_get_instruction_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetInstructionRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instruction.Instruction( + name='name_value', + display_name='display_name_value', + description='description_value', + data_type=dataset.DataType.IMAGE, + blocking_resources=['blocking_resources_value'], + )) + response = await client.get_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetInstructionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, instruction.Instruction) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.data_type == dataset.DataType.IMAGE + assert response.blocking_resources == ['blocking_resources_value'] + + +@pytest.mark.asyncio +async def test_get_instruction_async_from_dict(): + await test_get_instruction_async(request_type=dict) + + +def test_get_instruction_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetInstructionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instruction), + '__call__') as call: + call.return_value = instruction.Instruction() + client.get_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instruction_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetInstructionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instruction), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instruction.Instruction()) + await client.get_instruction(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_instruction_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instruction.Instruction() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instruction( + 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] + assert args[0].name == 'name_value' + + +def test_get_instruction_flattened_error(): + client = DataLabelingServiceClient( + 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_instruction( + data_labeling_service.GetInstructionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_instruction_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instruction.Instruction() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instruction.Instruction()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instruction( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_instruction_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_instruction( + data_labeling_service.GetInstructionRequest(), + name='name_value', + ) + + +def test_list_instructions(transport: str = 'grpc', request_type=data_labeling_service.ListInstructionsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instructions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListInstructionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_instructions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListInstructionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstructionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_instructions_from_dict(): + test_list_instructions(request_type=dict) + + +def test_list_instructions_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 = DataLabelingServiceClient( + 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_instructions), + '__call__') as call: + client.list_instructions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListInstructionsRequest() + + +@pytest.mark.asyncio +async def test_list_instructions_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListInstructionsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instructions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListInstructionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_instructions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListInstructionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstructionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_instructions_async_from_dict(): + await test_list_instructions_async(request_type=dict) + + +def test_list_instructions_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListInstructionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__') as call: + call.return_value = data_labeling_service.ListInstructionsResponse() + client.list_instructions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instructions_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListInstructionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListInstructionsResponse()) + await client.list_instructions(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_instructions_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListInstructionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instructions( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_instructions_flattened_error(): + client = DataLabelingServiceClient( + 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_instructions( + data_labeling_service.ListInstructionsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_instructions_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListInstructionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListInstructionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instructions( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_instructions_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_instructions( + data_labeling_service.ListInstructionsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_instructions_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + instruction.Instruction(), + ], + next_page_token='abc', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[], + next_page_token='def', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instructions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, instruction.Instruction) + for i in results) + +def test_list_instructions_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + instruction.Instruction(), + ], + next_page_token='abc', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[], + next_page_token='def', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instructions(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_instructions_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + instruction.Instruction(), + ], + next_page_token='abc', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[], + next_page_token='def', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instructions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instruction.Instruction) + for i in responses) + +@pytest.mark.asyncio +async def test_list_instructions_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instructions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + instruction.Instruction(), + ], + next_page_token='abc', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[], + next_page_token='def', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListInstructionsResponse( + instructions=[ + instruction.Instruction(), + instruction.Instruction(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_instructions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_instruction(transport: str = 'grpc', request_type=data_labeling_service.DeleteInstructionRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteInstructionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_instruction_from_dict(): + test_delete_instruction(request_type=dict) + + +def test_delete_instruction_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 = DataLabelingServiceClient( + 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_instruction), + '__call__') as call: + client.delete_instruction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteInstructionRequest() + + +@pytest.mark.asyncio +async def test_delete_instruction_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteInstructionRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteInstructionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_instruction_async_from_dict(): + await test_delete_instruction_async(request_type=dict) + + +def test_delete_instruction_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteInstructionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instruction), + '__call__') as call: + call.return_value = None + client.delete_instruction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instruction_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteInstructionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instruction), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_instruction(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_instruction_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_instruction( + 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] + assert args[0].name == 'name_value' + + +def test_delete_instruction_flattened_error(): + client = DataLabelingServiceClient( + 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_instruction( + data_labeling_service.DeleteInstructionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_instruction_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instruction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_instruction( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_instruction_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_instruction( + data_labeling_service.DeleteInstructionRequest(), + name='name_value', + ) + + +def test_get_evaluation(transport: str = 'grpc', request_type=data_labeling_service.GetEvaluationRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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', + annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, + evaluated_item_count=2129, + ) + 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] == data_labeling_service.GetEvaluationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == 'name_value' + assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION + assert response.evaluated_item_count == 2129 + + +def test_get_evaluation_from_dict(): + test_get_evaluation(request_type=dict) + + +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 = DataLabelingServiceClient( + 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] == data_labeling_service.GetEvaluationRequest() + + +@pytest.mark.asyncio +async def test_get_evaluation_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetEvaluationRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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', + annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, + evaluated_item_count=2129, + )) + 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] == data_labeling_service.GetEvaluationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == 'name_value' + assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION + assert response.evaluated_item_count == 2129 + + +@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 = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_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 = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_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 = DataLabelingServiceClient( + 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] + assert args[0].name == 'name_value' + + +def test_get_evaluation_flattened_error(): + client = DataLabelingServiceClient( + 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( + data_labeling_service.GetEvaluationRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_async(): + client = DataLabelingServiceAsyncClient( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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( + data_labeling_service.GetEvaluationRequest(), + name='name_value', + ) + + +def test_search_evaluations(transport: str = 'grpc', request_type=data_labeling_service.SearchEvaluationsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.SearchEvaluationsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_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] == data_labeling_service.SearchEvaluationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchEvaluationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_evaluations_from_dict(): + test_search_evaluations(request_type=dict) + + +def test_search_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 = DataLabelingServiceClient( + 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.search_evaluations), + '__call__') as call: + client.search_evaluations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.SearchEvaluationsRequest() + + +@pytest.mark.asyncio +async def test_search_evaluations_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.SearchEvaluationsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchEvaluationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.SearchEvaluationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchEvaluationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_evaluations_async_from_dict(): + await test_search_evaluations_async(request_type=dict) + + +def test_search_evaluations_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.SearchEvaluationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + call.return_value = data_labeling_service.SearchEvaluationsResponse() + client.search_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_search_evaluations_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.SearchEvaluationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchEvaluationsResponse()) + await client.search_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_search_evaluations_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.SearchEvaluationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_evaluations( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_search_evaluations_flattened_error(): + client = DataLabelingServiceClient( + 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.search_evaluations( + data_labeling_service.SearchEvaluationsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_search_evaluations_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.SearchEvaluationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchEvaluationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_evaluations( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_search_evaluations_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.search_evaluations( + data_labeling_service.SearchEvaluationsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_search_evaluations_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[], + next_page_token='def', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.search_evaluations(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) + for i in results) + +def test_search_evaluations_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[], + next_page_token='def', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = list(client.search_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_search_evaluations_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[], + next_page_token='def', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_evaluations(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.Evaluation) + for i in responses) + +@pytest.mark.asyncio +async def test_search_evaluations_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_evaluations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[], + next_page_token='def', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_evaluations(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_search_example_comparisons(transport: str = 'grpc', request_type=data_labeling_service.SearchExampleComparisonsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.SearchExampleComparisonsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_example_comparisons(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.SearchExampleComparisonsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchExampleComparisonsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_example_comparisons_from_dict(): + test_search_example_comparisons(request_type=dict) + + +def test_search_example_comparisons_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 = DataLabelingServiceClient( + 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.search_example_comparisons), + '__call__') as call: + client.search_example_comparisons() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.SearchExampleComparisonsRequest() + + +@pytest.mark.asyncio +async def test_search_example_comparisons_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.SearchExampleComparisonsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchExampleComparisonsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_example_comparisons(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.SearchExampleComparisonsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchExampleComparisonsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_example_comparisons_async_from_dict(): + await test_search_example_comparisons_async(request_type=dict) + + +def test_search_example_comparisons_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.SearchExampleComparisonsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + call.return_value = data_labeling_service.SearchExampleComparisonsResponse() + client.search_example_comparisons(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_search_example_comparisons_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.SearchExampleComparisonsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchExampleComparisonsResponse()) + await client.search_example_comparisons(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_search_example_comparisons_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.SearchExampleComparisonsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_example_comparisons( + 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] + assert args[0].parent == 'parent_value' + + +def test_search_example_comparisons_flattened_error(): + client = DataLabelingServiceClient( + 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.search_example_comparisons( + data_labeling_service.SearchExampleComparisonsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_search_example_comparisons_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.SearchExampleComparisonsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchExampleComparisonsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_example_comparisons( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_search_example_comparisons_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.search_example_comparisons( + data_labeling_service.SearchExampleComparisonsRequest(), + parent='parent_value', + ) + + +def test_search_example_comparisons_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[], + next_page_token='def', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.search_example_comparisons(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison) + for i in results) + +def test_search_example_comparisons_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[], + next_page_token='def', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + ), + RuntimeError, + ) + pages = list(client.search_example_comparisons(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_search_example_comparisons_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[], + next_page_token='def', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_example_comparisons(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison) + for i in responses) + +@pytest.mark.asyncio +async def test_search_example_comparisons_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_example_comparisons), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='abc', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[], + next_page_token='def', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + next_page_token='ghi', + ), + data_labeling_service.SearchExampleComparisonsResponse( + example_comparisons=[ + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_example_comparisons(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_create_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.CreateEvaluationJobRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_job.EvaluationJob( + name='name_value', + description='description_value', + state=evaluation_job.EvaluationJob.State.SCHEDULED, + schedule='schedule_value', + model_version='model_version_value', + annotation_spec_set='annotation_spec_set_value', + label_missing_ground_truth=True, + ) + response = client.create_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_job.EvaluationJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED + assert response.schedule == 'schedule_value' + assert response.model_version == 'model_version_value' + assert response.annotation_spec_set == 'annotation_spec_set_value' + assert response.label_missing_ground_truth is True + + +def test_create_evaluation_job_from_dict(): + test_create_evaluation_job(request_type=dict) + + +def test_create_evaluation_job_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 = DataLabelingServiceClient( + 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_evaluation_job), + '__call__') as call: + client.create_evaluation_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateEvaluationJobRequest() + + +@pytest.mark.asyncio +async def test_create_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateEvaluationJobRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob( + name='name_value', + description='description_value', + state=evaluation_job.EvaluationJob.State.SCHEDULED, + schedule='schedule_value', + model_version='model_version_value', + annotation_spec_set='annotation_spec_set_value', + label_missing_ground_truth=True, + )) + response = await client.create_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.CreateEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_job.EvaluationJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED + assert response.schedule == 'schedule_value' + assert response.model_version == 'model_version_value' + assert response.annotation_spec_set == 'annotation_spec_set_value' + assert response.label_missing_ground_truth is True + + +@pytest.mark.asyncio +async def test_create_evaluation_job_async_from_dict(): + await test_create_evaluation_job_async(request_type=dict) + + +def test_create_evaluation_job_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateEvaluationJobRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_job), + '__call__') as call: + call.return_value = evaluation_job.EvaluationJob() + client.create_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_evaluation_job_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.CreateEvaluationJobRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) + await client.create_evaluation_job(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_evaluation_job_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_job.EvaluationJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_evaluation_job( + parent='parent_value', + job=evaluation_job.EvaluationJob(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] + assert args[0].parent == 'parent_value' + assert args[0].job == evaluation_job.EvaluationJob(name='name_value') + + +def test_create_evaluation_job_flattened_error(): + client = DataLabelingServiceClient( + 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_evaluation_job( + data_labeling_service.CreateEvaluationJobRequest(), + parent='parent_value', + job=evaluation_job.EvaluationJob(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_evaluation_job_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_job.EvaluationJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_evaluation_job( + parent='parent_value', + job=evaluation_job.EvaluationJob(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] + assert args[0].parent == 'parent_value' + assert args[0].job == evaluation_job.EvaluationJob(name='name_value') + + +@pytest.mark.asyncio +async def test_create_evaluation_job_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_evaluation_job( + data_labeling_service.CreateEvaluationJobRequest(), + parent='parent_value', + job=evaluation_job.EvaluationJob(name='name_value'), + ) + + +def test_update_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.UpdateEvaluationJobRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_evaluation_job.EvaluationJob( + name='name_value', + description='description_value', + state=gcd_evaluation_job.EvaluationJob.State.SCHEDULED, + schedule='schedule_value', + model_version='model_version_value', + annotation_spec_set='annotation_spec_set_value', + label_missing_ground_truth=True, + ) + response = client.update_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.UpdateEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_evaluation_job.EvaluationJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == gcd_evaluation_job.EvaluationJob.State.SCHEDULED + assert response.schedule == 'schedule_value' + assert response.model_version == 'model_version_value' + assert response.annotation_spec_set == 'annotation_spec_set_value' + assert response.label_missing_ground_truth is True + + +def test_update_evaluation_job_from_dict(): + test_update_evaluation_job(request_type=dict) + + +def test_update_evaluation_job_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 = DataLabelingServiceClient( + 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_evaluation_job), + '__call__') as call: + client.update_evaluation_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.UpdateEvaluationJobRequest() + + +@pytest.mark.asyncio +async def test_update_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.UpdateEvaluationJobRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_evaluation_job.EvaluationJob( + name='name_value', + description='description_value', + state=gcd_evaluation_job.EvaluationJob.State.SCHEDULED, + schedule='schedule_value', + model_version='model_version_value', + annotation_spec_set='annotation_spec_set_value', + label_missing_ground_truth=True, + )) + response = await client.update_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.UpdateEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_evaluation_job.EvaluationJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == gcd_evaluation_job.EvaluationJob.State.SCHEDULED + assert response.schedule == 'schedule_value' + assert response.model_version == 'model_version_value' + assert response.annotation_spec_set == 'annotation_spec_set_value' + assert response.label_missing_ground_truth is True + + +@pytest.mark.asyncio +async def test_update_evaluation_job_async_from_dict(): + await test_update_evaluation_job_async(request_type=dict) + + +def test_update_evaluation_job_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.UpdateEvaluationJobRequest() + + request.evaluation_job.name = 'evaluation_job.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_job), + '__call__') as call: + call.return_value = gcd_evaluation_job.EvaluationJob() + client.update_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'evaluation_job.name=evaluation_job.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_evaluation_job_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.UpdateEvaluationJobRequest() + + request.evaluation_job.name = 'evaluation_job.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_evaluation_job.EvaluationJob()) + await client.update_evaluation_job(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', + 'evaluation_job.name=evaluation_job.name/value', + ) in kw['metadata'] + + +def test_update_evaluation_job_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_evaluation_job.EvaluationJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_evaluation_job( + evaluation_job=gcd_evaluation_job.EvaluationJob(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] + assert args[0].evaluation_job == gcd_evaluation_job.EvaluationJob(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_evaluation_job_flattened_error(): + client = DataLabelingServiceClient( + 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_evaluation_job( + data_labeling_service.UpdateEvaluationJobRequest(), + evaluation_job=gcd_evaluation_job.EvaluationJob(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_evaluation_job_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_evaluation_job.EvaluationJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_evaluation_job.EvaluationJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_evaluation_job( + evaluation_job=gcd_evaluation_job.EvaluationJob(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] + assert args[0].evaluation_job == gcd_evaluation_job.EvaluationJob(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_evaluation_job_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_evaluation_job( + data_labeling_service.UpdateEvaluationJobRequest(), + evaluation_job=gcd_evaluation_job.EvaluationJob(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.GetEvaluationJobRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_job.EvaluationJob( + name='name_value', + description='description_value', + state=evaluation_job.EvaluationJob.State.SCHEDULED, + schedule='schedule_value', + model_version='model_version_value', + annotation_spec_set='annotation_spec_set_value', + label_missing_ground_truth=True, + ) + response = client.get_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_job.EvaluationJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED + assert response.schedule == 'schedule_value' + assert response.model_version == 'model_version_value' + assert response.annotation_spec_set == 'annotation_spec_set_value' + assert response.label_missing_ground_truth is True + + +def test_get_evaluation_job_from_dict(): + test_get_evaluation_job(request_type=dict) + + +def test_get_evaluation_job_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 = DataLabelingServiceClient( + 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_job), + '__call__') as call: + client.get_evaluation_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetEvaluationJobRequest() + + +@pytest.mark.asyncio +async def test_get_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetEvaluationJobRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob( + name='name_value', + description='description_value', + state=evaluation_job.EvaluationJob.State.SCHEDULED, + schedule='schedule_value', + model_version='model_version_value', + annotation_spec_set='annotation_spec_set_value', + label_missing_ground_truth=True, + )) + response = await client.get_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.GetEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_job.EvaluationJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED + assert response.schedule == 'schedule_value' + assert response.model_version == 'model_version_value' + assert response.annotation_spec_set == 'annotation_spec_set_value' + assert response.label_missing_ground_truth is True + + +@pytest.mark.asyncio +async def test_get_evaluation_job_async_from_dict(): + await test_get_evaluation_job_async(request_type=dict) + + +def test_get_evaluation_job_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetEvaluationJobRequest() + + 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_job), + '__call__') as call: + call.return_value = evaluation_job.EvaluationJob() + client.get_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_job_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.GetEvaluationJobRequest() + + 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_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) + await client.get_evaluation_job(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_job_flattened(): + client = DataLabelingServiceClient( + 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_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_job.EvaluationJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +def test_get_evaluation_job_flattened_error(): + client = DataLabelingServiceClient( + 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_job( + data_labeling_service.GetEvaluationJobRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_job_flattened_async(): + client = DataLabelingServiceAsyncClient( + 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_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_job.EvaluationJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_evaluation_job_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_job( + data_labeling_service.GetEvaluationJobRequest(), + name='name_value', + ) + + +def test_pause_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.PauseEvaluationJobRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.pause_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.PauseEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_pause_evaluation_job_from_dict(): + test_pause_evaluation_job(request_type=dict) + + +def test_pause_evaluation_job_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 = DataLabelingServiceClient( + 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.pause_evaluation_job), + '__call__') as call: + client.pause_evaluation_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.PauseEvaluationJobRequest() + + +@pytest.mark.asyncio +async def test_pause_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.PauseEvaluationJobRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.pause_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.PauseEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_pause_evaluation_job_async_from_dict(): + await test_pause_evaluation_job_async(request_type=dict) + + +def test_pause_evaluation_job_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.PauseEvaluationJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_evaluation_job), + '__call__') as call: + call.return_value = None + client.pause_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_pause_evaluation_job_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.PauseEvaluationJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_evaluation_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.pause_evaluation_job(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_pause_evaluation_job_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.pause_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +def test_pause_evaluation_job_flattened_error(): + client = DataLabelingServiceClient( + 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.pause_evaluation_job( + data_labeling_service.PauseEvaluationJobRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_pause_evaluation_job_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.pause_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_pause_evaluation_job_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.pause_evaluation_job( + data_labeling_service.PauseEvaluationJobRequest(), + name='name_value', + ) + + +def test_resume_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.ResumeEvaluationJobRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.resume_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ResumeEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_resume_evaluation_job_from_dict(): + test_resume_evaluation_job(request_type=dict) + + +def test_resume_evaluation_job_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 = DataLabelingServiceClient( + 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.resume_evaluation_job), + '__call__') as call: + client.resume_evaluation_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ResumeEvaluationJobRequest() + + +@pytest.mark.asyncio +async def test_resume_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ResumeEvaluationJobRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.resume_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ResumeEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_resume_evaluation_job_async_from_dict(): + await test_resume_evaluation_job_async(request_type=dict) + + +def test_resume_evaluation_job_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ResumeEvaluationJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_evaluation_job), + '__call__') as call: + call.return_value = None + client.resume_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_resume_evaluation_job_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ResumeEvaluationJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_evaluation_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.resume_evaluation_job(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_resume_evaluation_job_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.resume_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +def test_resume_evaluation_job_flattened_error(): + client = DataLabelingServiceClient( + 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.resume_evaluation_job( + data_labeling_service.ResumeEvaluationJobRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_resume_evaluation_job_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.resume_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_resume_evaluation_job_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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.resume_evaluation_job( + data_labeling_service.ResumeEvaluationJobRequest(), + name='name_value', + ) + + +def test_delete_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.DeleteEvaluationJobRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_evaluation_job_from_dict(): + test_delete_evaluation_job(request_type=dict) + + +def test_delete_evaluation_job_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 = DataLabelingServiceClient( + 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_evaluation_job), + '__call__') as call: + client.delete_evaluation_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteEvaluationJobRequest() + + +@pytest.mark.asyncio +async def test_delete_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteEvaluationJobRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.DeleteEvaluationJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_evaluation_job_async_from_dict(): + await test_delete_evaluation_job_async(request_type=dict) + + +def test_delete_evaluation_job_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteEvaluationJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_job), + '__call__') as call: + call.return_value = None + client.delete_evaluation_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_evaluation_job_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.DeleteEvaluationJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation_job(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_evaluation_job_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +def test_delete_evaluation_job_flattened_error(): + client = DataLabelingServiceClient( + 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_evaluation_job( + data_labeling_service.DeleteEvaluationJobRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_evaluation_job_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_evaluation_job( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_evaluation_job_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_evaluation_job( + data_labeling_service.DeleteEvaluationJobRequest(), + name='name_value', + ) + + +def test_list_evaluation_jobs(transport: str = 'grpc', request_type=data_labeling_service.ListEvaluationJobsRequest): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListEvaluationJobsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_evaluation_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListEvaluationJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationJobsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_evaluation_jobs_from_dict(): + test_list_evaluation_jobs(request_type=dict) + + +def test_list_evaluation_jobs_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 = DataLabelingServiceClient( + 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_evaluation_jobs), + '__call__') as call: + client.list_evaluation_jobs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListEvaluationJobsRequest() + + +@pytest.mark.asyncio +async def test_list_evaluation_jobs_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListEvaluationJobsRequest): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListEvaluationJobsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_evaluation_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_labeling_service.ListEvaluationJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationJobsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_evaluation_jobs_async_from_dict(): + await test_list_evaluation_jobs_async(request_type=dict) + + +def test_list_evaluation_jobs_field_headers(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListEvaluationJobsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__') as call: + call.return_value = data_labeling_service.ListEvaluationJobsResponse() + client.list_evaluation_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_evaluation_jobs_field_headers_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_labeling_service.ListEvaluationJobsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListEvaluationJobsResponse()) + await client.list_evaluation_jobs(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_evaluation_jobs_flattened(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListEvaluationJobsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluation_jobs( + parent='parent_value', + filter='filter_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] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_evaluation_jobs_flattened_error(): + client = DataLabelingServiceClient( + 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_evaluation_jobs( + data_labeling_service.ListEvaluationJobsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_jobs_flattened_async(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_labeling_service.ListEvaluationJobsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListEvaluationJobsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluation_jobs( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_evaluation_jobs_flattened_error_async(): + client = DataLabelingServiceAsyncClient( + 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_evaluation_jobs( + data_labeling_service.ListEvaluationJobsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_evaluation_jobs_pager(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + next_page_token='abc', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[], + next_page_token='def', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_evaluation_jobs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, evaluation_job.EvaluationJob) + for i in results) + +def test_list_evaluation_jobs_pages(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + next_page_token='abc', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[], + next_page_token='def', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluation_jobs(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_evaluation_jobs_async_pager(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + next_page_token='abc', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[], + next_page_token='def', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluation_jobs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation_job.EvaluationJob) + for i in responses) + +@pytest.mark.asyncio +async def test_list_evaluation_jobs_async_pages(): + client = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + next_page_token='abc', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[], + next_page_token='def', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + ], + next_page_token='ghi', + ), + data_labeling_service.ListEvaluationJobsResponse( + evaluation_jobs=[ + evaluation_job.EvaluationJob(), + evaluation_job.EvaluationJob(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_evaluation_jobs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataLabelingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataLabelingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataLabelingServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataLabelingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataLabelingServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataLabelingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataLabelingServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataLabelingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataLabelingServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataLabelingServiceGrpcTransport, + transports.DataLabelingServiceGrpcAsyncIOTransport, +]) +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() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataLabelingServiceGrpcTransport, + ) + +def test_data_labeling_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataLabelingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_data_labeling_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataLabelingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_dataset', + 'get_dataset', + 'list_datasets', + 'delete_dataset', + 'import_data', + 'export_data', + 'get_data_item', + 'list_data_items', + 'get_annotated_dataset', + 'list_annotated_datasets', + 'delete_annotated_dataset', + 'label_image', + 'label_video', + 'label_text', + 'get_example', + 'list_examples', + 'create_annotation_spec_set', + 'get_annotation_spec_set', + 'list_annotation_spec_sets', + 'delete_annotation_spec_set', + 'create_instruction', + 'get_instruction', + 'list_instructions', + 'delete_instruction', + 'get_evaluation', + 'search_evaluations', + 'search_example_comparisons', + 'create_evaluation_job', + 'update_evaluation_job', + 'get_evaluation_job', + 'pause_evaluation_job', + 'resume_evaluation_job', + 'delete_evaluation_job', + 'list_evaluation_jobs', + ) + 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 + + +@requires_google_auth_gte_1_25_0 +def test_data_labeling_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.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataLabelingServiceTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_data_labeling_service_base_transport_with_credentials_file_old_google_auth(): + # 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.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataLabelingServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_data_labeling_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.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataLabelingServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_data_labeling_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) + DataLabelingServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_data_labeling_service_auth_adc_old_google_auth(): + # 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) + DataLabelingServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataLabelingServiceGrpcTransport, + transports.DataLabelingServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_data_labeling_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.DataLabelingServiceGrpcTransport, + transports.DataLabelingServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_data_labeling_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DataLabelingServiceGrpcTransport, grpc_helpers), + (transports.DataLabelingServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_data_labeling_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( + "datalabeling.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="datalabeling.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataLabelingServiceGrpcTransport, transports.DataLabelingServiceGrpcAsyncIOTransport]) +def test_data_labeling_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_data_labeling_service_host_no_port(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datalabeling.googleapis.com'), + ) + assert client.transport._host == 'datalabeling.googleapis.com:443' + + +def test_data_labeling_service_host_with_port(): + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datalabeling.googleapis.com:8000'), + ) + assert client.transport._host == 'datalabeling.googleapis.com:8000' + +def test_data_labeling_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataLabelingServiceGrpcTransport( + 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_data_labeling_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataLabelingServiceGrpcAsyncIOTransport( + 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.DataLabelingServiceGrpcTransport, transports.DataLabelingServiceGrpcAsyncIOTransport]) +def test_data_labeling_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.DataLabelingServiceGrpcTransport, transports.DataLabelingServiceGrpcAsyncIOTransport]) +def test_data_labeling_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_data_labeling_service_grpc_lro_client(): + client = DataLabelingServiceClient( + 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_data_labeling_service_grpc_lro_async_client(): + client = DataLabelingServiceAsyncClient( + 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_annotated_dataset_path(): + project = "squid" + dataset = "clam" + annotated_dataset = "whelk" + expected = "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, ) + actual = DataLabelingServiceClient.annotated_dataset_path(project, dataset, annotated_dataset) + assert expected == actual + + +def test_parse_annotated_dataset_path(): + expected = { + "project": "octopus", + "dataset": "oyster", + "annotated_dataset": "nudibranch", + } + path = DataLabelingServiceClient.annotated_dataset_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_annotated_dataset_path(path) + assert expected == actual + +def test_annotation_spec_set_path(): + project = "cuttlefish" + annotation_spec_set = "mussel" + expected = "projects/{project}/annotationSpecSets/{annotation_spec_set}".format(project=project, annotation_spec_set=annotation_spec_set, ) + actual = DataLabelingServiceClient.annotation_spec_set_path(project, annotation_spec_set) + assert expected == actual + + +def test_parse_annotation_spec_set_path(): + expected = { + "project": "winkle", + "annotation_spec_set": "nautilus", + } + path = DataLabelingServiceClient.annotation_spec_set_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_annotation_spec_set_path(path) + assert expected == actual + +def test_data_item_path(): + project = "scallop" + dataset = "abalone" + data_item = "squid" + expected = "projects/{project}/datasets/{dataset}/dataItems/{data_item}".format(project=project, dataset=dataset, data_item=data_item, ) + actual = DataLabelingServiceClient.data_item_path(project, dataset, data_item) + assert expected == actual + + +def test_parse_data_item_path(): + expected = { + "project": "clam", + "dataset": "whelk", + "data_item": "octopus", + } + path = DataLabelingServiceClient.data_item_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_data_item_path(path) + assert expected == actual + +def test_dataset_path(): + project = "oyster" + dataset = "nudibranch" + expected = "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) + actual = DataLabelingServiceClient.dataset_path(project, dataset) + assert expected == actual + + +def test_parse_dataset_path(): + expected = { + "project": "cuttlefish", + "dataset": "mussel", + } + path = DataLabelingServiceClient.dataset_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_dataset_path(path) + assert expected == actual + +def test_evaluation_path(): + project = "winkle" + dataset = "nautilus" + evaluation = "scallop" + expected = "projects/{project}/datasets/{dataset}/evaluations/{evaluation}".format(project=project, dataset=dataset, evaluation=evaluation, ) + actual = DataLabelingServiceClient.evaluation_path(project, dataset, evaluation) + assert expected == actual + + +def test_parse_evaluation_path(): + expected = { + "project": "abalone", + "dataset": "squid", + "evaluation": "clam", + } + path = DataLabelingServiceClient.evaluation_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_evaluation_path(path) + assert expected == actual + +def test_evaluation_job_path(): + project = "whelk" + evaluation_job = "octopus" + expected = "projects/{project}/evaluationJobs/{evaluation_job}".format(project=project, evaluation_job=evaluation_job, ) + actual = DataLabelingServiceClient.evaluation_job_path(project, evaluation_job) + assert expected == actual + + +def test_parse_evaluation_job_path(): + expected = { + "project": "oyster", + "evaluation_job": "nudibranch", + } + path = DataLabelingServiceClient.evaluation_job_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_evaluation_job_path(path) + assert expected == actual + +def test_example_path(): + project = "cuttlefish" + dataset = "mussel" + annotated_dataset = "winkle" + example = "nautilus" + expected = "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, ) + actual = DataLabelingServiceClient.example_path(project, dataset, annotated_dataset, example) + assert expected == actual + + +def test_parse_example_path(): + expected = { + "project": "scallop", + "dataset": "abalone", + "annotated_dataset": "squid", + "example": "clam", + } + path = DataLabelingServiceClient.example_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_example_path(path) + assert expected == actual + +def test_instruction_path(): + project = "whelk" + instruction = "octopus" + expected = "projects/{project}/instructions/{instruction}".format(project=project, instruction=instruction, ) + actual = DataLabelingServiceClient.instruction_path(project, instruction) + assert expected == actual + + +def test_parse_instruction_path(): + expected = { + "project": "oyster", + "instruction": "nudibranch", + } + path = DataLabelingServiceClient.instruction_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_instruction_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataLabelingServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DataLabelingServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataLabelingServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DataLabelingServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataLabelingServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DataLabelingServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DataLabelingServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DataLabelingServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.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 = DataLabelingServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DataLabelingServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataLabelingServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.DataLabelingServiceTransport, '_prep_wrapped_messages') as prep: + client = DataLabelingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataLabelingServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DataLabelingServiceClient.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 = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataLabelingServiceClient( + 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 = DataLabelingServiceClient( + 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() From 0d1cf30fab93b09c9208dd9b5cad8fe5ec78da5f Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 7 Oct 2021 19:32:31 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../data_labeling_service/async_client.py | 6 + .../services/data_labeling_service/client.py | 18 +- .../data_labeling_service/transports/base.py | 9 + .../data_labeling_service/transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../datalabeling_v1beta1/types/annotation.py | 15 + .../types/data_labeling_service.py | 43 + .../types/data_payloads.py | 4 + .../datalabeling_v1beta1/types/dataset.py | 7 + .../datalabeling_v1beta1/types/evaluation.py | 6 + .../types/evaluation_job.py | 1 + .../types/human_annotation_config.py | 9 + .../datalabeling_v1beta1/types/instruction.py | 1 + .../datalabeling_v1beta1/types/operations.py | 16 + owl-bot-staging/v1beta1/.coveragerc | 17 - owl-bot-staging/v1beta1/MANIFEST.in | 2 - owl-bot-staging/v1beta1/README.rst | 49 - owl-bot-staging/v1beta1/docs/conf.py | 376 - .../data_labeling_service.rst | 10 - .../docs/datalabeling_v1beta1/services.rst | 6 - .../docs/datalabeling_v1beta1/types.rst | 7 - owl-bot-staging/v1beta1/docs/index.rst | 7 - .../google/cloud/datalabeling/__init__.py | 293 - .../google/cloud/datalabeling/py.typed | 2 - .../cloud/datalabeling_v1beta1/__init__.py | 294 - .../datalabeling_v1beta1/gapic_metadata.json | 363 - .../cloud/datalabeling_v1beta1/py.typed | 2 - .../datalabeling_v1beta1/services/__init__.py | 15 - .../data_labeling_service/__init__.py | 22 - .../data_labeling_service/async_client.py | 3337 ----- .../services/data_labeling_service/client.py | 3451 ----- .../services/data_labeling_service/pagers.py | 1121 -- .../transports/__init__.py | 33 - .../data_labeling_service/transports/base.py | 802 -- .../data_labeling_service/transports/grpc.py | 1177 -- .../transports/grpc_asyncio.py | 1182 -- .../datalabeling_v1beta1/types/__init__.py | 308 - .../datalabeling_v1beta1/types/annotation.py | 688 - .../types/annotation_spec_set.py | 108 - .../types/data_labeling_service.py | 1375 -- .../types/data_payloads.py | 142 - .../datalabeling_v1beta1/types/dataset.py | 645 - .../datalabeling_v1beta1/types/evaluation.py | 405 - .../types/evaluation_job.py | 375 - .../types/human_annotation_config.py | 398 - .../datalabeling_v1beta1/types/instruction.py | 146 - .../datalabeling_v1beta1/types/operations.py | 549 - owl-bot-staging/v1beta1/mypy.ini | 3 - owl-bot-staging/v1beta1/noxfile.py | 132 - .../fixup_datalabeling_v1beta1_keywords.py | 209 - owl-bot-staging/v1beta1/setup.py | 54 - owl-bot-staging/v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../gapic/datalabeling_v1beta1/__init__.py | 16 - .../test_data_labeling_service.py | 10939 ---------------- .../test_data_labeling_service.py | 50 + 57 files changed, 187 insertions(+), 29112 deletions(-) delete mode 100644 owl-bot-staging/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta1/README.rst delete mode 100644 owl-bot-staging/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst delete mode 100644 owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst delete mode 100644 owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst delete mode 100644 owl-bot-staging/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py delete mode 100644 owl-bot-staging/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py delete mode 100644 owl-bot-staging/v1beta1/setup.py delete mode 100644 owl-bot-staging/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py diff --git a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py index 93325b9..3018c1a 100644 --- a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py +++ b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py @@ -3264,6 +3264,12 @@ async def list_evaluation_jobs( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py index 03d437c..97554e8 100644 --- a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py +++ b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py @@ -479,10 +479,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def create_dataset( @@ -3355,6 +3352,19 @@ def list_evaluation_jobs( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py index 75da4fc..42745e0 100644 --- a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py +++ b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py @@ -537,6 +537,15 @@ def _prep_wrapped_messages(self, 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) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py index bf83c01..42b93b3 100644 --- a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py +++ b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py @@ -1224,5 +1224,8 @@ def list_evaluation_jobs( ) return self._stubs["list_evaluation_jobs"] + def close(self): + self.grpc_channel.close() + __all__ = ("DataLabelingServiceGrpcTransport",) diff --git a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py index f067bfc..1c8ff43 100644 --- a/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py +++ b/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py @@ -1266,5 +1266,8 @@ def list_evaluation_jobs( ) return self._stubs["list_evaluation_jobs"] + def close(self): + return self.grpc_channel.close() + __all__ = ("DataLabelingServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/datalabeling_v1beta1/types/annotation.py b/google/cloud/datalabeling_v1beta1/types/annotation.py index 74ddc84..f905e2a 100644 --- a/google/cloud/datalabeling_v1beta1/types/annotation.py +++ b/google/cloud/datalabeling_v1beta1/types/annotation.py @@ -121,6 +121,7 @@ class Annotation(proto.Message): class AnnotationValue(proto.Message): r"""Annotation value for an example. + Attributes: image_classification_annotation (google.cloud.datalabeling_v1beta1.types.ImageClassificationAnnotation): Annotation value for image classification @@ -204,6 +205,7 @@ class AnnotationValue(proto.Message): class ImageClassificationAnnotation(proto.Message): r"""Image classification annotation definition. + Attributes: annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): Label of image. @@ -248,6 +250,7 @@ class NormalizedVertex(proto.Message): class BoundingPoly(proto.Message): r"""A bounding polygon in the image. + Attributes: vertices (Sequence[google.cloud.datalabeling_v1beta1.types.Vertex]): The bounding polygon vertices. @@ -258,6 +261,7 @@ class BoundingPoly(proto.Message): class NormalizedBoundingPoly(proto.Message): r"""Normalized bounding polygon. + Attributes: normalized_vertices (Sequence[google.cloud.datalabeling_v1beta1.types.NormalizedVertex]): The bounding polygon normalized vertices. @@ -294,6 +298,7 @@ class ImageBoundingPolyAnnotation(proto.Message): class Polyline(proto.Message): r"""A line with multiple line segments. + Attributes: vertices (Sequence[google.cloud.datalabeling_v1beta1.types.Vertex]): The polyline vertices. @@ -304,6 +309,7 @@ class Polyline(proto.Message): class NormalizedPolyline(proto.Message): r"""Normalized polyline. + Attributes: normalized_vertices (Sequence[google.cloud.datalabeling_v1beta1.types.NormalizedVertex]): The normalized polyline vertices. @@ -316,6 +322,7 @@ class NormalizedPolyline(proto.Message): class ImagePolylineAnnotation(proto.Message): r"""A polyline for the image annotation. + Attributes: polyline (google.cloud.datalabeling_v1beta1.types.Polyline): @@ -336,6 +343,7 @@ class ImagePolylineAnnotation(proto.Message): class ImageSegmentationAnnotation(proto.Message): r"""Image segmentation annotation. + Attributes: annotation_colors (Sequence[google.cloud.datalabeling_v1beta1.types.ImageSegmentationAnnotation.AnnotationColorsEntry]): The mapping between rgb color and annotation @@ -360,6 +368,7 @@ class ImageSegmentationAnnotation(proto.Message): class TextClassificationAnnotation(proto.Message): r"""Text classification annotation. + Attributes: annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): Label of the text. @@ -372,6 +381,7 @@ class TextClassificationAnnotation(proto.Message): class TextEntityExtractionAnnotation(proto.Message): r"""Text entity extraction annotation. + Attributes: annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): Label of the text entities. @@ -389,6 +399,7 @@ class TextEntityExtractionAnnotation(proto.Message): class SequentialSegment(proto.Message): r"""Start and end position in a sequence (e.g. text segment). + Attributes: start (int): Start position (inclusive). @@ -425,6 +436,7 @@ class TimeSegment(proto.Message): class VideoClassificationAnnotation(proto.Message): r"""Video classification annotation. + Attributes: time_segment (google.cloud.datalabeling_v1beta1.types.TimeSegment): The time segment of the video to which the @@ -464,6 +476,7 @@ class ObjectTrackingFrame(proto.Message): class VideoObjectTrackingAnnotation(proto.Message): r"""Video object tracking annotation. + Attributes: annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): Label of the object tracked in this @@ -487,6 +500,7 @@ class VideoObjectTrackingAnnotation(proto.Message): class VideoEventAnnotation(proto.Message): r"""Video event annotation. + Attributes: annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): Label of the event in this annotation. @@ -503,6 +517,7 @@ class VideoEventAnnotation(proto.Message): class AnnotationMetadata(proto.Message): r"""Additional information associated with the annotation. + Attributes: operator_metadata (google.cloud.datalabeling_v1beta1.types.OperatorMetadata): Metadata related to human labeling. diff --git a/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py b/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py index 35384e5..f7aed56 100644 --- a/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py +++ b/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py @@ -78,6 +78,7 @@ class CreateDatasetRequest(proto.Message): r"""Request message for CreateDataset. + Attributes: parent (str): Required. Dataset resource parent, format: @@ -92,6 +93,7 @@ class CreateDatasetRequest(proto.Message): class GetDatasetRequest(proto.Message): r"""Request message for GetDataSet. + Attributes: name (str): Required. Dataset resource name, format: @@ -103,6 +105,7 @@ class GetDatasetRequest(proto.Message): class ListDatasetsRequest(proto.Message): r"""Request message for ListDataset. + Attributes: parent (str): Required. Dataset resource parent, format: @@ -130,6 +133,7 @@ class ListDatasetsRequest(proto.Message): class ListDatasetsResponse(proto.Message): r"""Results of listing datasets within a project. + Attributes: datasets (Sequence[google.cloud.datalabeling_v1beta1.types.Dataset]): The list of datasets to return. @@ -149,6 +153,7 @@ def raw_page(self): class DeleteDatasetRequest(proto.Message): r"""Request message for DeleteDataset. + Attributes: name (str): Required. Dataset resource name, format: @@ -160,6 +165,7 @@ class DeleteDatasetRequest(proto.Message): class ImportDataRequest(proto.Message): r"""Request message for ImportData API. + Attributes: name (str): Required. Dataset resource name, format: @@ -182,6 +188,7 @@ class ImportDataRequest(proto.Message): class ExportDataRequest(proto.Message): r"""Request message for ExportData API. + Attributes: name (str): Required. Dataset resource name, format: @@ -214,6 +221,7 @@ class ExportDataRequest(proto.Message): class GetDataItemRequest(proto.Message): r"""Request message for GetDataItem. + Attributes: name (str): Required. The name of the data item to get, format: @@ -225,6 +233,7 @@ class GetDataItemRequest(proto.Message): class ListDataItemsRequest(proto.Message): r"""Request message for ListDataItems. + Attributes: parent (str): Required. Name of the dataset to list data items, format: @@ -252,6 +261,7 @@ class ListDataItemsRequest(proto.Message): class ListDataItemsResponse(proto.Message): r"""Results of listing data items in a dataset. + Attributes: data_items (Sequence[google.cloud.datalabeling_v1beta1.types.DataItem]): The list of data items to return. @@ -271,6 +281,7 @@ def raw_page(self): class GetAnnotatedDatasetRequest(proto.Message): r"""Request message for GetAnnotatedDataset. + Attributes: name (str): Required. Name of the annotated dataset to get, format: @@ -283,6 +294,7 @@ class GetAnnotatedDatasetRequest(proto.Message): class ListAnnotatedDatasetsRequest(proto.Message): r"""Request message for ListAnnotatedDatasets. + Attributes: parent (str): Required. Name of the dataset to list annotated datasets, @@ -310,6 +322,7 @@ class ListAnnotatedDatasetsRequest(proto.Message): class ListAnnotatedDatasetsResponse(proto.Message): r"""Results of listing annotated datasets for a dataset. + Attributes: annotated_datasets (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotatedDataset]): The list of annotated datasets to return. @@ -329,6 +342,7 @@ def raw_page(self): class DeleteAnnotatedDatasetRequest(proto.Message): r"""Request message for DeleteAnnotatedDataset. + Attributes: name (str): Required. Name of the annotated dataset to delete, format: @@ -341,6 +355,7 @@ class DeleteAnnotatedDatasetRequest(proto.Message): class LabelImageRequest(proto.Message): r"""Request message for starting an image labeling task. + Attributes: image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): Configuration for image classification task. One of @@ -410,6 +425,7 @@ class Feature(proto.Enum): class LabelVideoRequest(proto.Message): r"""Request message for LabelVideo. + Attributes: video_classification_config (google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig): Configuration for video classification task. One of @@ -477,6 +493,7 @@ class Feature(proto.Enum): class LabelTextRequest(proto.Message): r"""Request message for LabelText. + Attributes: text_classification_config (google.cloud.datalabeling_v1beta1.types.TextClassificationConfig): Configuration for text classification task. One of @@ -522,6 +539,7 @@ class Feature(proto.Enum): class GetExampleRequest(proto.Message): r"""Request message for GetExample + Attributes: name (str): Required. Name of example, format: @@ -539,6 +557,7 @@ class GetExampleRequest(proto.Message): class ListExamplesRequest(proto.Message): r"""Request message for ListExamples. + Attributes: parent (str): Required. Example resource parent. @@ -567,6 +586,7 @@ class ListExamplesRequest(proto.Message): class ListExamplesResponse(proto.Message): r"""Results of listing Examples in and annotated dataset. + Attributes: examples (Sequence[google.cloud.datalabeling_v1beta1.types.Example]): The list of examples to return. @@ -586,6 +606,7 @@ def raw_page(self): class CreateAnnotationSpecSetRequest(proto.Message): r"""Request message for CreateAnnotationSpecSet. + Attributes: parent (str): Required. AnnotationSpecSet resource parent, format: @@ -604,6 +625,7 @@ class CreateAnnotationSpecSetRequest(proto.Message): class GetAnnotationSpecSetRequest(proto.Message): r"""Request message for GetAnnotationSpecSet. + Attributes: name (str): Required. AnnotationSpecSet resource name, format: @@ -615,6 +637,7 @@ class GetAnnotationSpecSetRequest(proto.Message): class ListAnnotationSpecSetsRequest(proto.Message): r"""Request message for ListAnnotationSpecSets. + Attributes: parent (str): Required. Parent of AnnotationSpecSet resource, format: @@ -642,6 +665,7 @@ class ListAnnotationSpecSetsRequest(proto.Message): class ListAnnotationSpecSetsResponse(proto.Message): r"""Results of listing annotation spec set under a project. + Attributes: annotation_spec_sets (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet]): The list of annotation spec sets. @@ -661,6 +685,7 @@ def raw_page(self): class DeleteAnnotationSpecSetRequest(proto.Message): r"""Request message for DeleteAnnotationSpecSet. + Attributes: name (str): Required. AnnotationSpec resource name, format: @@ -672,6 +697,7 @@ class DeleteAnnotationSpecSetRequest(proto.Message): class CreateInstructionRequest(proto.Message): r"""Request message for CreateInstruction. + Attributes: parent (str): Required. Instruction resource parent, format: @@ -689,6 +715,7 @@ class CreateInstructionRequest(proto.Message): class GetInstructionRequest(proto.Message): r"""Request message for GetInstruction. + Attributes: name (str): Required. Instruction resource name, format: @@ -700,6 +727,7 @@ class GetInstructionRequest(proto.Message): class DeleteInstructionRequest(proto.Message): r"""Request message for DeleteInstruction. + Attributes: name (str): Required. Instruction resource name, format: @@ -711,6 +739,7 @@ class DeleteInstructionRequest(proto.Message): class ListInstructionsRequest(proto.Message): r"""Request message for ListInstructions. + Attributes: parent (str): Required. Instruction resource parent, format: @@ -738,6 +767,7 @@ class ListInstructionsRequest(proto.Message): class ListInstructionsResponse(proto.Message): r"""Results of listing instructions under a project. + Attributes: instructions (Sequence[google.cloud.datalabeling_v1beta1.types.Instruction]): The list of Instructions to return. @@ -757,6 +787,7 @@ def raw_page(self): class GetEvaluationRequest(proto.Message): r"""Request message for GetEvaluation. + Attributes: name (str): Required. Name of the evaluation. Format: @@ -769,6 +800,7 @@ class GetEvaluationRequest(proto.Message): class SearchEvaluationsRequest(proto.Message): r"""Request message for SearchEvaluation. + Attributes: parent (str): Required. Evaluation search parent (project ID). Format: @@ -827,6 +859,7 @@ class SearchEvaluationsRequest(proto.Message): class SearchEvaluationsResponse(proto.Message): r"""Results of searching evaluations. + Attributes: evaluations (Sequence[google.cloud.datalabeling_v1beta1.types.Evaluation]): The list of evaluations matching the search. @@ -846,6 +879,7 @@ def raw_page(self): class SearchExampleComparisonsRequest(proto.Message): r"""Request message of SearchExampleComparisons. + Attributes: parent (str): Required. Name of the @@ -874,6 +908,7 @@ class SearchExampleComparisonsRequest(proto.Message): class SearchExampleComparisonsResponse(proto.Message): r"""Results of searching example comparisons. + Attributes: example_comparisons (Sequence[google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse.ExampleComparison]): A list of example comparisons matching the @@ -912,6 +947,7 @@ def raw_page(self): class CreateEvaluationJobRequest(proto.Message): r"""Request message for CreateEvaluationJob. + Attributes: parent (str): Required. Evaluation job resource parent. Format: @@ -928,6 +964,7 @@ class CreateEvaluationJobRequest(proto.Message): class UpdateEvaluationJobRequest(proto.Message): r"""Request message for UpdateEvaluationJob. + Attributes: evaluation_job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): Required. Evaluation job that is going to be @@ -954,6 +991,7 @@ class UpdateEvaluationJobRequest(proto.Message): class GetEvaluationJobRequest(proto.Message): r"""Request message for GetEvaluationJob. + Attributes: name (str): Required. Name of the evaluation job. Format: @@ -966,6 +1004,7 @@ class GetEvaluationJobRequest(proto.Message): class PauseEvaluationJobRequest(proto.Message): r"""Request message for PauseEvaluationJob. + Attributes: name (str): Required. Name of the evaluation job that is going to be @@ -979,6 +1018,7 @@ class PauseEvaluationJobRequest(proto.Message): class ResumeEvaluationJobRequest(proto.Message): r"""Request message ResumeEvaluationJob. + Attributes: name (str): Required. Name of the evaluation job that is going to be @@ -992,6 +1032,7 @@ class ResumeEvaluationJobRequest(proto.Message): class DeleteEvaluationJobRequest(proto.Message): r"""Request message DeleteEvaluationJob. + Attributes: name (str): Required. Name of the evaluation job that is going to be @@ -1005,6 +1046,7 @@ class DeleteEvaluationJobRequest(proto.Message): class ListEvaluationJobsRequest(proto.Message): r"""Request message for ListEvaluationJobs. + Attributes: parent (str): Required. Evaluation job resource parent. Format: @@ -1040,6 +1082,7 @@ class ListEvaluationJobsRequest(proto.Message): class ListEvaluationJobsResponse(proto.Message): r"""Results for listing evaluation jobs. + Attributes: evaluation_jobs (Sequence[google.cloud.datalabeling_v1beta1.types.EvaluationJob]): The list of evaluation jobs to return. diff --git a/google/cloud/datalabeling_v1beta1/types/data_payloads.py b/google/cloud/datalabeling_v1beta1/types/data_payloads.py index bb70d32..1461f6e 100644 --- a/google/cloud/datalabeling_v1beta1/types/data_payloads.py +++ b/google/cloud/datalabeling_v1beta1/types/data_payloads.py @@ -26,6 +26,7 @@ class ImagePayload(proto.Message): r"""Container of information about an image. + Attributes: mime_type (str): Image format. @@ -46,6 +47,7 @@ class ImagePayload(proto.Message): class TextPayload(proto.Message): r"""Container of information about a piece of text. + Attributes: text_content (str): Text content. @@ -56,6 +58,7 @@ class TextPayload(proto.Message): class VideoThumbnail(proto.Message): r"""Container of information of a video thumbnail. + Attributes: thumbnail (bytes): A byte string of the video frame. @@ -71,6 +74,7 @@ class VideoThumbnail(proto.Message): class VideoPayload(proto.Message): r"""Container of information of a video. + Attributes: mime_type (str): Video format. diff --git a/google/cloud/datalabeling_v1beta1/types/dataset.py b/google/cloud/datalabeling_v1beta1/types/dataset.py index e5abd68..e50fb30 100644 --- a/google/cloud/datalabeling_v1beta1/types/dataset.py +++ b/google/cloud/datalabeling_v1beta1/types/dataset.py @@ -142,6 +142,7 @@ class InputConfig(proto.Message): class TextMetadata(proto.Message): r"""Metadata for the text. + Attributes: language_code (str): The language of this text, as a @@ -154,6 +155,7 @@ class TextMetadata(proto.Message): class ClassificationMetadata(proto.Message): r"""Metadata for classification annotations. + Attributes: is_multi_label (bool): Whether the classification task is multi- @@ -165,6 +167,7 @@ class ClassificationMetadata(proto.Message): class GcsSource(proto.Message): r"""Source of the Cloud Storage file to be imported. + Attributes: input_uri (str): Required. The input URI of source file. This must be a Cloud @@ -208,6 +211,7 @@ class BigQuerySource(proto.Message): class OutputConfig(proto.Message): r"""The configuration of output data. + Attributes: gcs_destination (google.cloud.datalabeling_v1beta1.types.GcsDestination): Output to a file in Cloud Storage. Should be @@ -245,6 +249,7 @@ class GcsDestination(proto.Message): class GcsFolderDestination(proto.Message): r"""Export folder destination of the data. + Attributes: output_folder_uri (str): Required. Cloud Storage directory to export @@ -349,6 +354,7 @@ class AnnotatedDataset(proto.Message): class LabelStats(proto.Message): r"""Statistics about annotation specs. + Attributes: example_count (Sequence[google.cloud.datalabeling_v1beta1.types.LabelStats.ExampleCountEntry]): Map of each annotation spec's example count. @@ -365,6 +371,7 @@ class LabelStats(proto.Message): class AnnotatedDatasetMetadata(proto.Message): r"""Metadata on AnnotatedDataset. + Attributes: image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): Configuration for image classification task. diff --git a/google/cloud/datalabeling_v1beta1/types/evaluation.py b/google/cloud/datalabeling_v1beta1/types/evaluation.py index ea72b33..0bd1ff8 100644 --- a/google/cloud/datalabeling_v1beta1/types/evaluation.py +++ b/google/cloud/datalabeling_v1beta1/types/evaluation.py @@ -107,6 +107,7 @@ class EvaluationConfig(proto.Message): class BoundingBoxEvaluationOptions(proto.Message): r"""Options regarding evaluation between bounding boxes. + Attributes: iou_threshold (float): Minimum [intersection-over-union @@ -121,6 +122,7 @@ class BoundingBoxEvaluationOptions(proto.Message): class EvaluationMetrics(proto.Message): r""" + Attributes: classification_metrics (google.cloud.datalabeling_v1beta1.types.ClassificationMetrics): @@ -138,6 +140,7 @@ class EvaluationMetrics(proto.Message): class ClassificationMetrics(proto.Message): r"""Metrics calculated for a classification model. + Attributes: pr_curve (google.cloud.datalabeling_v1beta1.types.PrCurve): Precision-recall curve based on ground truth @@ -166,6 +169,7 @@ class ObjectDetectionMetrics(proto.Message): class PrCurve(proto.Message): r""" + Attributes: annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): The annotation spec of the label for which @@ -186,6 +190,7 @@ class PrCurve(proto.Message): class ConfidenceMetricsEntry(proto.Message): r""" + Attributes: confidence_threshold (float): Threshold used for this entry. @@ -263,6 +268,7 @@ class ConfusionMatrix(proto.Message): class ConfusionMatrixEntry(proto.Message): r""" + Attributes: annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): The annotation spec of a predicted label. diff --git a/google/cloud/datalabeling_v1beta1/types/evaluation_job.py b/google/cloud/datalabeling_v1beta1/types/evaluation_job.py index 4ca05fc..e9186a9 100644 --- a/google/cloud/datalabeling_v1beta1/types/evaluation_job.py +++ b/google/cloud/datalabeling_v1beta1/types/evaluation_job.py @@ -301,6 +301,7 @@ class EvaluationJobAlertConfig(proto.Message): class Attempt(proto.Message): r"""Records a failed evaluation job run. + Attributes: attempt_time (google.protobuf.timestamp_pb2.Timestamp): diff --git a/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py b/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py index 567a941..06e953a 100644 --- a/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py +++ b/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py @@ -48,6 +48,7 @@ class StringAggregationType(proto.Enum): class HumanAnnotationConfig(proto.Message): r"""Configuration for how human labeling task should be done. + Attributes: instruction (str): Required. Instruction resource name. @@ -108,6 +109,7 @@ class HumanAnnotationConfig(proto.Message): class ImageClassificationConfig(proto.Message): r"""Config for image classification human labeling task. + Attributes: annotation_spec_set (str): Required. Annotation spec set resource name. @@ -144,6 +146,7 @@ class BoundingPolyConfig(proto.Message): class PolylineConfig(proto.Message): r"""Config for image polyline human labeling task. + Attributes: annotation_spec_set (str): Required. Annotation spec set resource name. @@ -158,6 +161,7 @@ class PolylineConfig(proto.Message): class SegmentationConfig(proto.Message): r"""Config for image segmentation + Attributes: annotation_spec_set (str): Required. Annotation spec set resource name. format: @@ -234,6 +238,7 @@ class ObjectDetectionConfig(proto.Message): class ObjectTrackingConfig(proto.Message): r"""Config for video object tracking human labeling task. + Attributes: annotation_spec_set (str): Required. Annotation spec set resource name. @@ -244,6 +249,7 @@ class ObjectTrackingConfig(proto.Message): class EventConfig(proto.Message): r"""Config for video event human labeling task. + Attributes: annotation_spec_sets (Sequence[str]): Required. The list of annotation spec set @@ -257,6 +263,7 @@ class EventConfig(proto.Message): class TextClassificationConfig(proto.Message): r"""Config for text classification human labeling task. + Attributes: allow_multi_label (bool): Optional. If allow_multi_label is true, contributors are @@ -274,6 +281,7 @@ class TextClassificationConfig(proto.Message): class SentimentConfig(proto.Message): r"""Config for setting up sentiments. + Attributes: enable_label_sentiment_selection (bool): If set to true, contributors will have the @@ -287,6 +295,7 @@ class SentimentConfig(proto.Message): class TextEntityExtractionConfig(proto.Message): r"""Config for text entity extraction human labeling task. + Attributes: annotation_spec_set (str): Required. Annotation spec set resource name. diff --git a/google/cloud/datalabeling_v1beta1/types/instruction.py b/google/cloud/datalabeling_v1beta1/types/instruction.py index 4479bfd..1af72eb 100644 --- a/google/cloud/datalabeling_v1beta1/types/instruction.py +++ b/google/cloud/datalabeling_v1beta1/types/instruction.py @@ -91,6 +91,7 @@ class CsvInstruction(proto.Message): class PdfInstruction(proto.Message): r"""Instruction from a PDF file. + Attributes: gcs_file_uri (str): PDF file for the instruction. Only gcs path diff --git a/google/cloud/datalabeling_v1beta1/types/operations.py b/google/cloud/datalabeling_v1beta1/types/operations.py index c99585f..e7f37c4 100644 --- a/google/cloud/datalabeling_v1beta1/types/operations.py +++ b/google/cloud/datalabeling_v1beta1/types/operations.py @@ -48,6 +48,7 @@ class ImportDataOperationResponse(proto.Message): r"""Response used for ImportData longrunning operation. + Attributes: dataset (str): Ouptut only. The name of imported dataset. @@ -66,6 +67,7 @@ class ImportDataOperationResponse(proto.Message): class ExportDataOperationResponse(proto.Message): r"""Response used for ExportDataset longrunning operation. + Attributes: dataset (str): Ouptut only. The name of dataset. "projects/*/datasets/*". @@ -93,6 +95,7 @@ class ExportDataOperationResponse(proto.Message): class ImportDataOperationMetadata(proto.Message): r"""Metadata of an ImportData operation. + Attributes: dataset (str): Output only. The name of imported dataset. @@ -116,6 +119,7 @@ class ImportDataOperationMetadata(proto.Message): class ExportDataOperationMetadata(proto.Message): r"""Metadata of an ExportData operation. + Attributes: dataset (str): Output only. The name of dataset to be exported. @@ -271,6 +275,7 @@ class LabelOperationMetadata(proto.Message): class LabelImageClassificationOperationMetadata(proto.Message): r"""Metadata of a LabelImageClassification operation. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -284,6 +289,7 @@ class LabelImageClassificationOperationMetadata(proto.Message): class LabelImageBoundingBoxOperationMetadata(proto.Message): r"""Details of a LabelImageBoundingBox operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -311,6 +317,7 @@ class LabelImageOrientedBoundingBoxOperationMetadata(proto.Message): class LabelImageBoundingPolyOperationMetadata(proto.Message): r"""Details of LabelImageBoundingPoly operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -324,6 +331,7 @@ class LabelImageBoundingPolyOperationMetadata(proto.Message): class LabelImagePolylineOperationMetadata(proto.Message): r"""Details of LabelImagePolyline operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -337,6 +345,7 @@ class LabelImagePolylineOperationMetadata(proto.Message): class LabelImageSegmentationOperationMetadata(proto.Message): r"""Details of a LabelImageSegmentation operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config. @@ -349,6 +358,7 @@ class LabelImageSegmentationOperationMetadata(proto.Message): class LabelVideoClassificationOperationMetadata(proto.Message): r"""Details of a LabelVideoClassification operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -362,6 +372,7 @@ class LabelVideoClassificationOperationMetadata(proto.Message): class LabelVideoObjectDetectionOperationMetadata(proto.Message): r"""Details of a LabelVideoObjectDetection operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -375,6 +386,7 @@ class LabelVideoObjectDetectionOperationMetadata(proto.Message): class LabelVideoObjectTrackingOperationMetadata(proto.Message): r"""Details of a LabelVideoObjectTracking operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -388,6 +400,7 @@ class LabelVideoObjectTrackingOperationMetadata(proto.Message): class LabelVideoEventOperationMetadata(proto.Message): r"""Details of a LabelVideoEvent operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -401,6 +414,7 @@ class LabelVideoEventOperationMetadata(proto.Message): class LabelTextClassificationOperationMetadata(proto.Message): r"""Details of a LabelTextClassification operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -414,6 +428,7 @@ class LabelTextClassificationOperationMetadata(proto.Message): class LabelTextEntityExtractionOperationMetadata(proto.Message): r"""Details of a LabelTextEntityExtraction operation metadata. + Attributes: basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): Basic human annotation config used in @@ -427,6 +442,7 @@ class LabelTextEntityExtractionOperationMetadata(proto.Message): class CreateInstructionMetadata(proto.Message): r"""Metadata of a CreateInstruction operation. + Attributes: instruction (str): The name of the created Instruction. diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc deleted file mode 100644 index ecbc77f..0000000 --- a/owl-bot-staging/v1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/datalabeling/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in deleted file mode 100644 index 2b92910..0000000 --- a/owl-bot-staging/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/datalabeling *.py -recursive-include google/cloud/datalabeling_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst deleted file mode 100644 index 15c3d97..0000000 --- a/owl-bot-staging/v1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Datalabeling 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 Datalabeling 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py deleted file mode 100644 index ccd09d6..0000000 --- a/owl-bot-staging/v1beta1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datalabeling 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-datalabeling" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-datalabeling-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 = [ - ( - master_doc, - "google-cloud-datalabeling.tex", - u"google-cloud-datalabeling 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 = [ - ( - master_doc, - "google-cloud-datalabeling", - u"Google Cloud Datalabeling 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 = [ - ( - master_doc, - "google-cloud-datalabeling", - u"google-cloud-datalabeling Documentation", - author, - "google-cloud-datalabeling", - "GAPIC library for Google Cloud Datalabeling 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/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst deleted file mode 100644 index d2524a1..0000000 --- a/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/data_labeling_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DataLabelingService -------------------------------------- - -.. automodule:: google.cloud.datalabeling_v1beta1.services.data_labeling_service - :members: - :inherited-members: - -.. automodule:: google.cloud.datalabeling_v1beta1.services.data_labeling_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst deleted file mode 100644 index 2ddfb76..0000000 --- a/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Datalabeling v1beta1 API -================================================== -.. toctree:: - :maxdepth: 2 - - data_labeling_service diff --git a/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst deleted file mode 100644 index 452ea6c..0000000 --- a/owl-bot-staging/v1beta1/docs/datalabeling_v1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Datalabeling v1beta1 API -=============================================== - -.. automodule:: google.cloud.datalabeling_v1beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst deleted file mode 100644 index b73f31f..0000000 --- a/owl-bot-staging/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - datalabeling_v1beta1/services - datalabeling_v1beta1/types diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py deleted file mode 100644 index 41cb770..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling/__init__.py +++ /dev/null @@ -1,293 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.datalabeling_v1beta1.services.data_labeling_service.client import DataLabelingServiceClient -from google.cloud.datalabeling_v1beta1.services.data_labeling_service.async_client import DataLabelingServiceAsyncClient - -from google.cloud.datalabeling_v1beta1.types.annotation import Annotation -from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationMetadata -from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationValue -from google.cloud.datalabeling_v1beta1.types.annotation import BoundingPoly -from google.cloud.datalabeling_v1beta1.types.annotation import ImageBoundingPolyAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import ImageClassificationAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import ImagePolylineAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import ImageSegmentationAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import NormalizedBoundingPoly -from google.cloud.datalabeling_v1beta1.types.annotation import NormalizedPolyline -from google.cloud.datalabeling_v1beta1.types.annotation import NormalizedVertex -from google.cloud.datalabeling_v1beta1.types.annotation import ObjectTrackingFrame -from google.cloud.datalabeling_v1beta1.types.annotation import OperatorMetadata -from google.cloud.datalabeling_v1beta1.types.annotation import Polyline -from google.cloud.datalabeling_v1beta1.types.annotation import SequentialSegment -from google.cloud.datalabeling_v1beta1.types.annotation import TextClassificationAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import TextEntityExtractionAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import TimeSegment -from google.cloud.datalabeling_v1beta1.types.annotation import Vertex -from google.cloud.datalabeling_v1beta1.types.annotation import VideoClassificationAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import VideoEventAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import VideoObjectTrackingAnnotation -from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationSentiment -from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationSource -from google.cloud.datalabeling_v1beta1.types.annotation import AnnotationType -from google.cloud.datalabeling_v1beta1.types.annotation_spec_set import AnnotationSpec -from google.cloud.datalabeling_v1beta1.types.annotation_spec_set import AnnotationSpecSet -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateAnnotationSpecSetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateDatasetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateEvaluationJobRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import CreateInstructionRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteAnnotatedDatasetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteAnnotationSpecSetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteDatasetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteEvaluationJobRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import DeleteInstructionRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ExportDataRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetAnnotatedDatasetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetAnnotationSpecSetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetDataItemRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetDatasetRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetEvaluationJobRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetEvaluationRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetExampleRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import GetInstructionRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ImportDataRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import LabelImageRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import LabelTextRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import LabelVideoRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotatedDatasetsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotatedDatasetsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotationSpecSetsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListAnnotationSpecSetsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDataItemsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDataItemsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDatasetsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListDatasetsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListEvaluationJobsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListEvaluationJobsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListExamplesRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListExamplesResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListInstructionsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ListInstructionsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import PauseEvaluationJobRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import ResumeEvaluationJobRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchEvaluationsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchEvaluationsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchExampleComparisonsRequest -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import SearchExampleComparisonsResponse -from google.cloud.datalabeling_v1beta1.types.data_labeling_service import UpdateEvaluationJobRequest -from google.cloud.datalabeling_v1beta1.types.data_payloads import ImagePayload -from google.cloud.datalabeling_v1beta1.types.data_payloads import TextPayload -from google.cloud.datalabeling_v1beta1.types.data_payloads import VideoPayload -from google.cloud.datalabeling_v1beta1.types.data_payloads import VideoThumbnail -from google.cloud.datalabeling_v1beta1.types.dataset import AnnotatedDataset -from google.cloud.datalabeling_v1beta1.types.dataset import AnnotatedDatasetMetadata -from google.cloud.datalabeling_v1beta1.types.dataset import BigQuerySource -from google.cloud.datalabeling_v1beta1.types.dataset import ClassificationMetadata -from google.cloud.datalabeling_v1beta1.types.dataset import DataItem -from google.cloud.datalabeling_v1beta1.types.dataset import Dataset -from google.cloud.datalabeling_v1beta1.types.dataset import Example -from google.cloud.datalabeling_v1beta1.types.dataset import GcsDestination -from google.cloud.datalabeling_v1beta1.types.dataset import GcsFolderDestination -from google.cloud.datalabeling_v1beta1.types.dataset import GcsSource -from google.cloud.datalabeling_v1beta1.types.dataset import InputConfig -from google.cloud.datalabeling_v1beta1.types.dataset import LabelStats -from google.cloud.datalabeling_v1beta1.types.dataset import OutputConfig -from google.cloud.datalabeling_v1beta1.types.dataset import TextMetadata -from google.cloud.datalabeling_v1beta1.types.dataset import DataType -from google.cloud.datalabeling_v1beta1.types.evaluation import BoundingBoxEvaluationOptions -from google.cloud.datalabeling_v1beta1.types.evaluation import ClassificationMetrics -from google.cloud.datalabeling_v1beta1.types.evaluation import ConfusionMatrix -from google.cloud.datalabeling_v1beta1.types.evaluation import Evaluation -from google.cloud.datalabeling_v1beta1.types.evaluation import EvaluationConfig -from google.cloud.datalabeling_v1beta1.types.evaluation import EvaluationMetrics -from google.cloud.datalabeling_v1beta1.types.evaluation import ObjectDetectionMetrics -from google.cloud.datalabeling_v1beta1.types.evaluation import PrCurve -from google.cloud.datalabeling_v1beta1.types.evaluation_job import Attempt -from google.cloud.datalabeling_v1beta1.types.evaluation_job import EvaluationJob -from google.cloud.datalabeling_v1beta1.types.evaluation_job import EvaluationJobAlertConfig -from google.cloud.datalabeling_v1beta1.types.evaluation_job import EvaluationJobConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import BoundingPolyConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import EventConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import HumanAnnotationConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import ImageClassificationConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import ObjectDetectionConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import ObjectTrackingConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import PolylineConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import SegmentationConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import SentimentConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import TextClassificationConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import TextEntityExtractionConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import VideoClassificationConfig -from google.cloud.datalabeling_v1beta1.types.human_annotation_config import StringAggregationType -from google.cloud.datalabeling_v1beta1.types.instruction import CsvInstruction -from google.cloud.datalabeling_v1beta1.types.instruction import Instruction -from google.cloud.datalabeling_v1beta1.types.instruction import PdfInstruction -from google.cloud.datalabeling_v1beta1.types.operations import CreateInstructionMetadata -from google.cloud.datalabeling_v1beta1.types.operations import ExportDataOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import ExportDataOperationResponse -from google.cloud.datalabeling_v1beta1.types.operations import ImportDataOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import ImportDataOperationResponse -from google.cloud.datalabeling_v1beta1.types.operations import LabelImageBoundingBoxOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelImageBoundingPolyOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelImageClassificationOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelImageOrientedBoundingBoxOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelImagePolylineOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelImageSegmentationOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelTextClassificationOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelTextEntityExtractionOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoClassificationOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoEventOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoObjectDetectionOperationMetadata -from google.cloud.datalabeling_v1beta1.types.operations import LabelVideoObjectTrackingOperationMetadata - -__all__ = ('DataLabelingServiceClient', - 'DataLabelingServiceAsyncClient', - 'Annotation', - 'AnnotationMetadata', - 'AnnotationValue', - 'BoundingPoly', - 'ImageBoundingPolyAnnotation', - 'ImageClassificationAnnotation', - 'ImagePolylineAnnotation', - 'ImageSegmentationAnnotation', - 'NormalizedBoundingPoly', - 'NormalizedPolyline', - 'NormalizedVertex', - 'ObjectTrackingFrame', - 'OperatorMetadata', - 'Polyline', - 'SequentialSegment', - 'TextClassificationAnnotation', - 'TextEntityExtractionAnnotation', - 'TimeSegment', - 'Vertex', - 'VideoClassificationAnnotation', - 'VideoEventAnnotation', - 'VideoObjectTrackingAnnotation', - 'AnnotationSentiment', - 'AnnotationSource', - 'AnnotationType', - 'AnnotationSpec', - 'AnnotationSpecSet', - 'CreateAnnotationSpecSetRequest', - 'CreateDatasetRequest', - 'CreateEvaluationJobRequest', - 'CreateInstructionRequest', - 'DeleteAnnotatedDatasetRequest', - 'DeleteAnnotationSpecSetRequest', - 'DeleteDatasetRequest', - 'DeleteEvaluationJobRequest', - 'DeleteInstructionRequest', - 'ExportDataRequest', - 'GetAnnotatedDatasetRequest', - 'GetAnnotationSpecSetRequest', - 'GetDataItemRequest', - 'GetDatasetRequest', - 'GetEvaluationJobRequest', - 'GetEvaluationRequest', - 'GetExampleRequest', - 'GetInstructionRequest', - 'ImportDataRequest', - 'LabelImageRequest', - 'LabelTextRequest', - 'LabelVideoRequest', - 'ListAnnotatedDatasetsRequest', - 'ListAnnotatedDatasetsResponse', - 'ListAnnotationSpecSetsRequest', - 'ListAnnotationSpecSetsResponse', - 'ListDataItemsRequest', - 'ListDataItemsResponse', - 'ListDatasetsRequest', - 'ListDatasetsResponse', - 'ListEvaluationJobsRequest', - 'ListEvaluationJobsResponse', - 'ListExamplesRequest', - 'ListExamplesResponse', - 'ListInstructionsRequest', - 'ListInstructionsResponse', - 'PauseEvaluationJobRequest', - 'ResumeEvaluationJobRequest', - 'SearchEvaluationsRequest', - 'SearchEvaluationsResponse', - 'SearchExampleComparisonsRequest', - 'SearchExampleComparisonsResponse', - 'UpdateEvaluationJobRequest', - 'ImagePayload', - 'TextPayload', - 'VideoPayload', - 'VideoThumbnail', - 'AnnotatedDataset', - 'AnnotatedDatasetMetadata', - 'BigQuerySource', - 'ClassificationMetadata', - 'DataItem', - 'Dataset', - 'Example', - 'GcsDestination', - 'GcsFolderDestination', - 'GcsSource', - 'InputConfig', - 'LabelStats', - 'OutputConfig', - 'TextMetadata', - 'DataType', - 'BoundingBoxEvaluationOptions', - 'ClassificationMetrics', - 'ConfusionMatrix', - 'Evaluation', - 'EvaluationConfig', - 'EvaluationMetrics', - 'ObjectDetectionMetrics', - 'PrCurve', - 'Attempt', - 'EvaluationJob', - 'EvaluationJobAlertConfig', - 'EvaluationJobConfig', - 'BoundingPolyConfig', - 'EventConfig', - 'HumanAnnotationConfig', - 'ImageClassificationConfig', - 'ObjectDetectionConfig', - 'ObjectTrackingConfig', - 'PolylineConfig', - 'SegmentationConfig', - 'SentimentConfig', - 'TextClassificationConfig', - 'TextEntityExtractionConfig', - 'VideoClassificationConfig', - 'StringAggregationType', - 'CsvInstruction', - 'Instruction', - 'PdfInstruction', - 'CreateInstructionMetadata', - 'ExportDataOperationMetadata', - 'ExportDataOperationResponse', - 'ImportDataOperationMetadata', - 'ImportDataOperationResponse', - 'LabelImageBoundingBoxOperationMetadata', - 'LabelImageBoundingPolyOperationMetadata', - 'LabelImageClassificationOperationMetadata', - 'LabelImageOrientedBoundingBoxOperationMetadata', - 'LabelImagePolylineOperationMetadata', - 'LabelImageSegmentationOperationMetadata', - 'LabelOperationMetadata', - 'LabelTextClassificationOperationMetadata', - 'LabelTextEntityExtractionOperationMetadata', - 'LabelVideoClassificationOperationMetadata', - 'LabelVideoEventOperationMetadata', - 'LabelVideoObjectDetectionOperationMetadata', - 'LabelVideoObjectTrackingOperationMetadata', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed b/owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed deleted file mode 100644 index 1d27d78..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-datalabeling package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py deleted file mode 100644 index ff186c4..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/__init__.py +++ /dev/null @@ -1,294 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .services.data_labeling_service import DataLabelingServiceClient -from .services.data_labeling_service import DataLabelingServiceAsyncClient - -from .types.annotation import Annotation -from .types.annotation import AnnotationMetadata -from .types.annotation import AnnotationValue -from .types.annotation import BoundingPoly -from .types.annotation import ImageBoundingPolyAnnotation -from .types.annotation import ImageClassificationAnnotation -from .types.annotation import ImagePolylineAnnotation -from .types.annotation import ImageSegmentationAnnotation -from .types.annotation import NormalizedBoundingPoly -from .types.annotation import NormalizedPolyline -from .types.annotation import NormalizedVertex -from .types.annotation import ObjectTrackingFrame -from .types.annotation import OperatorMetadata -from .types.annotation import Polyline -from .types.annotation import SequentialSegment -from .types.annotation import TextClassificationAnnotation -from .types.annotation import TextEntityExtractionAnnotation -from .types.annotation import TimeSegment -from .types.annotation import Vertex -from .types.annotation import VideoClassificationAnnotation -from .types.annotation import VideoEventAnnotation -from .types.annotation import VideoObjectTrackingAnnotation -from .types.annotation import AnnotationSentiment -from .types.annotation import AnnotationSource -from .types.annotation import AnnotationType -from .types.annotation_spec_set import AnnotationSpec -from .types.annotation_spec_set import AnnotationSpecSet -from .types.data_labeling_service import CreateAnnotationSpecSetRequest -from .types.data_labeling_service import CreateDatasetRequest -from .types.data_labeling_service import CreateEvaluationJobRequest -from .types.data_labeling_service import CreateInstructionRequest -from .types.data_labeling_service import DeleteAnnotatedDatasetRequest -from .types.data_labeling_service import DeleteAnnotationSpecSetRequest -from .types.data_labeling_service import DeleteDatasetRequest -from .types.data_labeling_service import DeleteEvaluationJobRequest -from .types.data_labeling_service import DeleteInstructionRequest -from .types.data_labeling_service import ExportDataRequest -from .types.data_labeling_service import GetAnnotatedDatasetRequest -from .types.data_labeling_service import GetAnnotationSpecSetRequest -from .types.data_labeling_service import GetDataItemRequest -from .types.data_labeling_service import GetDatasetRequest -from .types.data_labeling_service import GetEvaluationJobRequest -from .types.data_labeling_service import GetEvaluationRequest -from .types.data_labeling_service import GetExampleRequest -from .types.data_labeling_service import GetInstructionRequest -from .types.data_labeling_service import ImportDataRequest -from .types.data_labeling_service import LabelImageRequest -from .types.data_labeling_service import LabelTextRequest -from .types.data_labeling_service import LabelVideoRequest -from .types.data_labeling_service import ListAnnotatedDatasetsRequest -from .types.data_labeling_service import ListAnnotatedDatasetsResponse -from .types.data_labeling_service import ListAnnotationSpecSetsRequest -from .types.data_labeling_service import ListAnnotationSpecSetsResponse -from .types.data_labeling_service import ListDataItemsRequest -from .types.data_labeling_service import ListDataItemsResponse -from .types.data_labeling_service import ListDatasetsRequest -from .types.data_labeling_service import ListDatasetsResponse -from .types.data_labeling_service import ListEvaluationJobsRequest -from .types.data_labeling_service import ListEvaluationJobsResponse -from .types.data_labeling_service import ListExamplesRequest -from .types.data_labeling_service import ListExamplesResponse -from .types.data_labeling_service import ListInstructionsRequest -from .types.data_labeling_service import ListInstructionsResponse -from .types.data_labeling_service import PauseEvaluationJobRequest -from .types.data_labeling_service import ResumeEvaluationJobRequest -from .types.data_labeling_service import SearchEvaluationsRequest -from .types.data_labeling_service import SearchEvaluationsResponse -from .types.data_labeling_service import SearchExampleComparisonsRequest -from .types.data_labeling_service import SearchExampleComparisonsResponse -from .types.data_labeling_service import UpdateEvaluationJobRequest -from .types.data_payloads import ImagePayload -from .types.data_payloads import TextPayload -from .types.data_payloads import VideoPayload -from .types.data_payloads import VideoThumbnail -from .types.dataset import AnnotatedDataset -from .types.dataset import AnnotatedDatasetMetadata -from .types.dataset import BigQuerySource -from .types.dataset import ClassificationMetadata -from .types.dataset import DataItem -from .types.dataset import Dataset -from .types.dataset import Example -from .types.dataset import GcsDestination -from .types.dataset import GcsFolderDestination -from .types.dataset import GcsSource -from .types.dataset import InputConfig -from .types.dataset import LabelStats -from .types.dataset import OutputConfig -from .types.dataset import TextMetadata -from .types.dataset import DataType -from .types.evaluation import BoundingBoxEvaluationOptions -from .types.evaluation import ClassificationMetrics -from .types.evaluation import ConfusionMatrix -from .types.evaluation import Evaluation -from .types.evaluation import EvaluationConfig -from .types.evaluation import EvaluationMetrics -from .types.evaluation import ObjectDetectionMetrics -from .types.evaluation import PrCurve -from .types.evaluation_job import Attempt -from .types.evaluation_job import EvaluationJob -from .types.evaluation_job import EvaluationJobAlertConfig -from .types.evaluation_job import EvaluationJobConfig -from .types.human_annotation_config import BoundingPolyConfig -from .types.human_annotation_config import EventConfig -from .types.human_annotation_config import HumanAnnotationConfig -from .types.human_annotation_config import ImageClassificationConfig -from .types.human_annotation_config import ObjectDetectionConfig -from .types.human_annotation_config import ObjectTrackingConfig -from .types.human_annotation_config import PolylineConfig -from .types.human_annotation_config import SegmentationConfig -from .types.human_annotation_config import SentimentConfig -from .types.human_annotation_config import TextClassificationConfig -from .types.human_annotation_config import TextEntityExtractionConfig -from .types.human_annotation_config import VideoClassificationConfig -from .types.human_annotation_config import StringAggregationType -from .types.instruction import CsvInstruction -from .types.instruction import Instruction -from .types.instruction import PdfInstruction -from .types.operations import CreateInstructionMetadata -from .types.operations import ExportDataOperationMetadata -from .types.operations import ExportDataOperationResponse -from .types.operations import ImportDataOperationMetadata -from .types.operations import ImportDataOperationResponse -from .types.operations import LabelImageBoundingBoxOperationMetadata -from .types.operations import LabelImageBoundingPolyOperationMetadata -from .types.operations import LabelImageClassificationOperationMetadata -from .types.operations import LabelImageOrientedBoundingBoxOperationMetadata -from .types.operations import LabelImagePolylineOperationMetadata -from .types.operations import LabelImageSegmentationOperationMetadata -from .types.operations import LabelOperationMetadata -from .types.operations import LabelTextClassificationOperationMetadata -from .types.operations import LabelTextEntityExtractionOperationMetadata -from .types.operations import LabelVideoClassificationOperationMetadata -from .types.operations import LabelVideoEventOperationMetadata -from .types.operations import LabelVideoObjectDetectionOperationMetadata -from .types.operations import LabelVideoObjectTrackingOperationMetadata - -__all__ = ( - 'DataLabelingServiceAsyncClient', -'AnnotatedDataset', -'AnnotatedDatasetMetadata', -'Annotation', -'AnnotationMetadata', -'AnnotationSentiment', -'AnnotationSource', -'AnnotationSpec', -'AnnotationSpecSet', -'AnnotationType', -'AnnotationValue', -'Attempt', -'BigQuerySource', -'BoundingBoxEvaluationOptions', -'BoundingPoly', -'BoundingPolyConfig', -'ClassificationMetadata', -'ClassificationMetrics', -'ConfusionMatrix', -'CreateAnnotationSpecSetRequest', -'CreateDatasetRequest', -'CreateEvaluationJobRequest', -'CreateInstructionMetadata', -'CreateInstructionRequest', -'CsvInstruction', -'DataItem', -'DataLabelingServiceClient', -'DataType', -'Dataset', -'DeleteAnnotatedDatasetRequest', -'DeleteAnnotationSpecSetRequest', -'DeleteDatasetRequest', -'DeleteEvaluationJobRequest', -'DeleteInstructionRequest', -'Evaluation', -'EvaluationConfig', -'EvaluationJob', -'EvaluationJobAlertConfig', -'EvaluationJobConfig', -'EvaluationMetrics', -'EventConfig', -'Example', -'ExportDataOperationMetadata', -'ExportDataOperationResponse', -'ExportDataRequest', -'GcsDestination', -'GcsFolderDestination', -'GcsSource', -'GetAnnotatedDatasetRequest', -'GetAnnotationSpecSetRequest', -'GetDataItemRequest', -'GetDatasetRequest', -'GetEvaluationJobRequest', -'GetEvaluationRequest', -'GetExampleRequest', -'GetInstructionRequest', -'HumanAnnotationConfig', -'ImageBoundingPolyAnnotation', -'ImageClassificationAnnotation', -'ImageClassificationConfig', -'ImagePayload', -'ImagePolylineAnnotation', -'ImageSegmentationAnnotation', -'ImportDataOperationMetadata', -'ImportDataOperationResponse', -'ImportDataRequest', -'InputConfig', -'Instruction', -'LabelImageBoundingBoxOperationMetadata', -'LabelImageBoundingPolyOperationMetadata', -'LabelImageClassificationOperationMetadata', -'LabelImageOrientedBoundingBoxOperationMetadata', -'LabelImagePolylineOperationMetadata', -'LabelImageRequest', -'LabelImageSegmentationOperationMetadata', -'LabelOperationMetadata', -'LabelStats', -'LabelTextClassificationOperationMetadata', -'LabelTextEntityExtractionOperationMetadata', -'LabelTextRequest', -'LabelVideoClassificationOperationMetadata', -'LabelVideoEventOperationMetadata', -'LabelVideoObjectDetectionOperationMetadata', -'LabelVideoObjectTrackingOperationMetadata', -'LabelVideoRequest', -'ListAnnotatedDatasetsRequest', -'ListAnnotatedDatasetsResponse', -'ListAnnotationSpecSetsRequest', -'ListAnnotationSpecSetsResponse', -'ListDataItemsRequest', -'ListDataItemsResponse', -'ListDatasetsRequest', -'ListDatasetsResponse', -'ListEvaluationJobsRequest', -'ListEvaluationJobsResponse', -'ListExamplesRequest', -'ListExamplesResponse', -'ListInstructionsRequest', -'ListInstructionsResponse', -'NormalizedBoundingPoly', -'NormalizedPolyline', -'NormalizedVertex', -'ObjectDetectionConfig', -'ObjectDetectionMetrics', -'ObjectTrackingConfig', -'ObjectTrackingFrame', -'OperatorMetadata', -'OutputConfig', -'PauseEvaluationJobRequest', -'PdfInstruction', -'Polyline', -'PolylineConfig', -'PrCurve', -'ResumeEvaluationJobRequest', -'SearchEvaluationsRequest', -'SearchEvaluationsResponse', -'SearchExampleComparisonsRequest', -'SearchExampleComparisonsResponse', -'SegmentationConfig', -'SentimentConfig', -'SequentialSegment', -'StringAggregationType', -'TextClassificationAnnotation', -'TextClassificationConfig', -'TextEntityExtractionAnnotation', -'TextEntityExtractionConfig', -'TextMetadata', -'TextPayload', -'TimeSegment', -'UpdateEvaluationJobRequest', -'Vertex', -'VideoClassificationAnnotation', -'VideoClassificationConfig', -'VideoEventAnnotation', -'VideoObjectTrackingAnnotation', -'VideoPayload', -'VideoThumbnail', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json deleted file mode 100644 index d98e553..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,363 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.datalabeling_v1beta1", - "protoPackage": "google.cloud.datalabeling.v1beta1", - "schema": "1.0", - "services": { - "DataLabelingService": { - "clients": { - "grpc": { - "libraryClient": "DataLabelingServiceClient", - "rpcs": { - "CreateAnnotationSpecSet": { - "methods": [ - "create_annotation_spec_set" - ] - }, - "CreateDataset": { - "methods": [ - "create_dataset" - ] - }, - "CreateEvaluationJob": { - "methods": [ - "create_evaluation_job" - ] - }, - "CreateInstruction": { - "methods": [ - "create_instruction" - ] - }, - "DeleteAnnotatedDataset": { - "methods": [ - "delete_annotated_dataset" - ] - }, - "DeleteAnnotationSpecSet": { - "methods": [ - "delete_annotation_spec_set" - ] - }, - "DeleteDataset": { - "methods": [ - "delete_dataset" - ] - }, - "DeleteEvaluationJob": { - "methods": [ - "delete_evaluation_job" - ] - }, - "DeleteInstruction": { - "methods": [ - "delete_instruction" - ] - }, - "ExportData": { - "methods": [ - "export_data" - ] - }, - "GetAnnotatedDataset": { - "methods": [ - "get_annotated_dataset" - ] - }, - "GetAnnotationSpecSet": { - "methods": [ - "get_annotation_spec_set" - ] - }, - "GetDataItem": { - "methods": [ - "get_data_item" - ] - }, - "GetDataset": { - "methods": [ - "get_dataset" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetEvaluationJob": { - "methods": [ - "get_evaluation_job" - ] - }, - "GetExample": { - "methods": [ - "get_example" - ] - }, - "GetInstruction": { - "methods": [ - "get_instruction" - ] - }, - "ImportData": { - "methods": [ - "import_data" - ] - }, - "LabelImage": { - "methods": [ - "label_image" - ] - }, - "LabelText": { - "methods": [ - "label_text" - ] - }, - "LabelVideo": { - "methods": [ - "label_video" - ] - }, - "ListAnnotatedDatasets": { - "methods": [ - "list_annotated_datasets" - ] - }, - "ListAnnotationSpecSets": { - "methods": [ - "list_annotation_spec_sets" - ] - }, - "ListDataItems": { - "methods": [ - "list_data_items" - ] - }, - "ListDatasets": { - "methods": [ - "list_datasets" - ] - }, - "ListEvaluationJobs": { - "methods": [ - "list_evaluation_jobs" - ] - }, - "ListExamples": { - "methods": [ - "list_examples" - ] - }, - "ListInstructions": { - "methods": [ - "list_instructions" - ] - }, - "PauseEvaluationJob": { - "methods": [ - "pause_evaluation_job" - ] - }, - "ResumeEvaluationJob": { - "methods": [ - "resume_evaluation_job" - ] - }, - "SearchEvaluations": { - "methods": [ - "search_evaluations" - ] - }, - "SearchExampleComparisons": { - "methods": [ - "search_example_comparisons" - ] - }, - "UpdateEvaluationJob": { - "methods": [ - "update_evaluation_job" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DataLabelingServiceAsyncClient", - "rpcs": { - "CreateAnnotationSpecSet": { - "methods": [ - "create_annotation_spec_set" - ] - }, - "CreateDataset": { - "methods": [ - "create_dataset" - ] - }, - "CreateEvaluationJob": { - "methods": [ - "create_evaluation_job" - ] - }, - "CreateInstruction": { - "methods": [ - "create_instruction" - ] - }, - "DeleteAnnotatedDataset": { - "methods": [ - "delete_annotated_dataset" - ] - }, - "DeleteAnnotationSpecSet": { - "methods": [ - "delete_annotation_spec_set" - ] - }, - "DeleteDataset": { - "methods": [ - "delete_dataset" - ] - }, - "DeleteEvaluationJob": { - "methods": [ - "delete_evaluation_job" - ] - }, - "DeleteInstruction": { - "methods": [ - "delete_instruction" - ] - }, - "ExportData": { - "methods": [ - "export_data" - ] - }, - "GetAnnotatedDataset": { - "methods": [ - "get_annotated_dataset" - ] - }, - "GetAnnotationSpecSet": { - "methods": [ - "get_annotation_spec_set" - ] - }, - "GetDataItem": { - "methods": [ - "get_data_item" - ] - }, - "GetDataset": { - "methods": [ - "get_dataset" - ] - }, - "GetEvaluation": { - "methods": [ - "get_evaluation" - ] - }, - "GetEvaluationJob": { - "methods": [ - "get_evaluation_job" - ] - }, - "GetExample": { - "methods": [ - "get_example" - ] - }, - "GetInstruction": { - "methods": [ - "get_instruction" - ] - }, - "ImportData": { - "methods": [ - "import_data" - ] - }, - "LabelImage": { - "methods": [ - "label_image" - ] - }, - "LabelText": { - "methods": [ - "label_text" - ] - }, - "LabelVideo": { - "methods": [ - "label_video" - ] - }, - "ListAnnotatedDatasets": { - "methods": [ - "list_annotated_datasets" - ] - }, - "ListAnnotationSpecSets": { - "methods": [ - "list_annotation_spec_sets" - ] - }, - "ListDataItems": { - "methods": [ - "list_data_items" - ] - }, - "ListDatasets": { - "methods": [ - "list_datasets" - ] - }, - "ListEvaluationJobs": { - "methods": [ - "list_evaluation_jobs" - ] - }, - "ListExamples": { - "methods": [ - "list_examples" - ] - }, - "ListInstructions": { - "methods": [ - "list_instructions" - ] - }, - "PauseEvaluationJob": { - "methods": [ - "pause_evaluation_job" - ] - }, - "ResumeEvaluationJob": { - "methods": [ - "resume_evaluation_job" - ] - }, - "SearchEvaluations": { - "methods": [ - "search_evaluations" - ] - }, - "SearchExampleComparisons": { - "methods": [ - "search_example_comparisons" - ] - }, - "UpdateEvaluationJob": { - "methods": [ - "update_evaluation_job" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed deleted file mode 100644 index 1d27d78..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-datalabeling package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py deleted file mode 100644 index 7926b83..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DataLabelingServiceClient -from .async_client import DataLabelingServiceAsyncClient - -__all__ = ( - 'DataLabelingServiceClient', - 'DataLabelingServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py deleted file mode 100644 index 68e4f79..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/async_client.py +++ /dev/null @@ -1,3337 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.datalabeling_v1beta1.services.data_labeling_service import pagers -from google.cloud.datalabeling_v1beta1.types import annotation -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import data_labeling_service -from google.cloud.datalabeling_v1beta1.types import data_payloads -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job -from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job -from google.cloud.datalabeling_v1beta1.types import human_annotation_config -from google.cloud.datalabeling_v1beta1.types import instruction -from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction -from google.cloud.datalabeling_v1beta1.types import operations -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DataLabelingServiceGrpcAsyncIOTransport -from .client import DataLabelingServiceClient - - -class DataLabelingServiceAsyncClient: - """Service for the AI Platform Data Labeling API.""" - - _client: DataLabelingServiceClient - - DEFAULT_ENDPOINT = DataLabelingServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DataLabelingServiceClient.DEFAULT_MTLS_ENDPOINT - - annotated_dataset_path = staticmethod(DataLabelingServiceClient.annotated_dataset_path) - parse_annotated_dataset_path = staticmethod(DataLabelingServiceClient.parse_annotated_dataset_path) - annotation_spec_set_path = staticmethod(DataLabelingServiceClient.annotation_spec_set_path) - parse_annotation_spec_set_path = staticmethod(DataLabelingServiceClient.parse_annotation_spec_set_path) - data_item_path = staticmethod(DataLabelingServiceClient.data_item_path) - parse_data_item_path = staticmethod(DataLabelingServiceClient.parse_data_item_path) - dataset_path = staticmethod(DataLabelingServiceClient.dataset_path) - parse_dataset_path = staticmethod(DataLabelingServiceClient.parse_dataset_path) - evaluation_path = staticmethod(DataLabelingServiceClient.evaluation_path) - parse_evaluation_path = staticmethod(DataLabelingServiceClient.parse_evaluation_path) - evaluation_job_path = staticmethod(DataLabelingServiceClient.evaluation_job_path) - parse_evaluation_job_path = staticmethod(DataLabelingServiceClient.parse_evaluation_job_path) - example_path = staticmethod(DataLabelingServiceClient.example_path) - parse_example_path = staticmethod(DataLabelingServiceClient.parse_example_path) - instruction_path = staticmethod(DataLabelingServiceClient.instruction_path) - parse_instruction_path = staticmethod(DataLabelingServiceClient.parse_instruction_path) - common_billing_account_path = staticmethod(DataLabelingServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DataLabelingServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DataLabelingServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DataLabelingServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DataLabelingServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DataLabelingServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DataLabelingServiceClient.common_project_path) - parse_common_project_path = staticmethod(DataLabelingServiceClient.parse_common_project_path) - common_location_path = staticmethod(DataLabelingServiceClient.common_location_path) - parse_common_location_path = staticmethod(DataLabelingServiceClient.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: - DataLabelingServiceAsyncClient: The constructed client. - """ - return DataLabelingServiceClient.from_service_account_info.__func__(DataLabelingServiceAsyncClient, 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: - DataLabelingServiceAsyncClient: The constructed client. - """ - return DataLabelingServiceClient.from_service_account_file.__func__(DataLabelingServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DataLabelingServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DataLabelingServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DataLabelingServiceClient).get_transport_class, type(DataLabelingServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, DataLabelingServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data labeling 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, ~.DataLabelingServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DataLabelingServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_dataset(self, - request: data_labeling_service.CreateDatasetRequest = None, - *, - parent: str = None, - dataset: gcd_dataset.Dataset = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_dataset.Dataset: - r"""Creates dataset. If success return a Dataset - resource. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.CreateDatasetRequest`): - The request object. Request message for CreateDataset. - parent (:class:`str`): - Required. Dataset resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - dataset (:class:`google.cloud.datalabeling_v1beta1.types.Dataset`): - Required. The dataset to be created. - 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.datalabeling_v1beta1.types.Dataset: - Dataset is the resource to hold your - data. You can request multiple labeling - tasks for a dataset while each one will - generate an AnnotatedDataset. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, 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 = data_labeling_service.CreateDatasetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - 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.create_dataset, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_dataset(self, - request: data_labeling_service.GetDatasetRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.Dataset: - r"""Gets dataset by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetDatasetRequest`): - The request object. Request message for GetDataSet. - name (:class:`str`): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - 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.datalabeling_v1beta1.types.Dataset: - Dataset is the resource to hold your - data. You can request multiple labeling - tasks for a dataset while each one will - generate an AnnotatedDataset. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.GetDatasetRequest(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, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_datasets(self, - request: data_labeling_service.ListDatasetsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDatasetsAsyncPager: - r"""Lists datasets under a project. Pagination is - supported. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsRequest`): - The request object. Request message for ListDataset. - parent (:class:`str`): - Required. Dataset resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. Filter on dataset is not - supported at this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDatasetsAsyncPager: - Results of listing datasets within a - project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.ListDatasetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_datasets, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDatasetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_dataset(self, - request: data_labeling_service.DeleteDatasetRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a dataset by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteDatasetRequest`): - The request object. Request message for DeleteDataset. - name (:class:`str`): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.DeleteDatasetRequest(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_dataset, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_data(self, - request: data_labeling_service.ImportDataRequest = None, - *, - name: str = None, - input_config: dataset.InputConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports data into dataset based on source locations - defined in request. It can be called multiple times for - the same dataset. Each dataset can only have one long - running operation running on it. For example, no - labeling task (also long running operation) can be - started while importing is still ongoing. Vice versa. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ImportDataRequest`): - The request object. Request message for ImportData API. - name (:class:`str`): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (:class:`google.cloud.datalabeling_v1beta1.types.InputConfig`): - Required. Specify the input source of - the data. - - This corresponds to the ``input_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.datalabeling_v1beta1.types.ImportDataOperationResponse` - Response used for ImportData longrunning operation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, input_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 = data_labeling_service.ImportDataRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if input_config is not None: - request.input_config = input_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.import_data, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - operations.ImportDataOperationResponse, - metadata_type=operations.ImportDataOperationMetadata, - ) - - # Done; return the response. - return response - - async def export_data(self, - request: data_labeling_service.ExportDataRequest = None, - *, - name: str = None, - annotated_dataset: str = None, - filter: str = None, - output_config: dataset.OutputConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports data and annotations from dataset. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ExportDataRequest`): - The request object. Request message for ExportData API. - name (:class:`str`): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - annotated_dataset (:class:`str`): - Required. Annotated dataset resource name. DataItem in - Dataset and their annotations in specified annotated - dataset will be exported. It's in format of - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - - This corresponds to the ``annotated_dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - output_config (:class:`google.cloud.datalabeling_v1beta1.types.OutputConfig`): - Required. Specify the output - destination. - - This corresponds to the ``output_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.datalabeling_v1beta1.types.ExportDataOperationResponse` - Response used for ExportDataset longrunning operation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, annotated_dataset, filter, output_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 = data_labeling_service.ExportDataRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if annotated_dataset is not None: - request.annotated_dataset = annotated_dataset - if filter is not None: - request.filter = filter - if output_config is not None: - request.output_config = output_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.export_data, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - operations.ExportDataOperationResponse, - metadata_type=operations.ExportDataOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_data_item(self, - request: data_labeling_service.GetDataItemRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.DataItem: - r"""Gets a data item in a dataset by resource name. This - API can be called after data are imported into dataset. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetDataItemRequest`): - The request object. Request message for GetDataItem. - name (:class:`str`): - Required. The name of the data item to get, format: - projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} - - 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.datalabeling_v1beta1.types.DataItem: - DataItem is a piece of data, without - annotation. For example, an image. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.GetDataItemRequest(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_data_item, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_data_items(self, - request: data_labeling_service.ListDataItemsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataItemsAsyncPager: - r"""Lists data items in a dataset. This API can be called - after data are imported into dataset. Pagination is - supported. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsRequest`): - The request object. Request message for ListDataItems. - parent (:class:`str`): - Required. Name of the dataset to list data items, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDataItemsAsyncPager: - Results of listing data items in a - dataset. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.ListDataItemsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_data_items, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDataItemsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_annotated_dataset(self, - request: data_labeling_service.GetAnnotatedDatasetRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.AnnotatedDataset: - r"""Gets an annotated dataset by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetAnnotatedDatasetRequest`): - The request object. Request message for - GetAnnotatedDataset. - name (:class:`str`): - Required. Name of the annotated dataset to get, format: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - - 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.datalabeling_v1beta1.types.AnnotatedDataset: - AnnotatedDataset is a set holding - annotations for data in a Dataset. Each - labeling task will generate an - AnnotatedDataset under the Dataset that - the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.GetAnnotatedDatasetRequest(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_annotated_dataset, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_annotated_datasets(self, - request: data_labeling_service.ListAnnotatedDatasetsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnnotatedDatasetsAsyncPager: - r"""Lists annotated datasets for a dataset. Pagination is - supported. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest`): - The request object. Request message for - ListAnnotatedDatasets. - parent (:class:`str`): - Required. Name of the dataset to list annotated - datasets, format: - projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotatedDatasetsAsyncPager: - Results of listing annotated datasets - for a dataset. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.ListAnnotatedDatasetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_annotated_datasets, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAnnotatedDatasetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_annotated_dataset(self, - request: data_labeling_service.DeleteAnnotatedDatasetRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an annotated dataset by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteAnnotatedDatasetRequest`): - The request object. Request message for - DeleteAnnotatedDataset. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - request = data_labeling_service.DeleteAnnotatedDatasetRequest(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.delete_annotated_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(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def label_image(self, - request: data_labeling_service.LabelImageRequest = None, - *, - parent: str = None, - basic_config: human_annotation_config.HumanAnnotationConfig = None, - feature: data_labeling_service.LabelImageRequest.Feature = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a labeling task for image. The type of image - labeling task is configured by feature in the request. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.LabelImageRequest`): - The request object. Request message for starting an - image labeling task. - parent (:class:`str`): - Required. Name of the dataset to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - basic_config (:class:`google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig`): - Required. Basic human annotation - config. - - This corresponds to the ``basic_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - feature (:class:`google.cloud.datalabeling_v1beta1.types.LabelImageRequest.Feature`): - Required. The type of image labeling - task. - - This corresponds to the ``feature`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each - labeling task will generate an AnnotatedDataset under - the Dataset that the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, basic_config, feature]) - if request is 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 = data_labeling_service.LabelImageRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if basic_config is not None: - request.basic_config = basic_config - if feature is not None: - request.feature = feature - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.label_image, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - dataset.AnnotatedDataset, - metadata_type=operations.LabelOperationMetadata, - ) - - # Done; return the response. - return response - - async def label_video(self, - request: data_labeling_service.LabelVideoRequest = None, - *, - parent: str = None, - basic_config: human_annotation_config.HumanAnnotationConfig = None, - feature: data_labeling_service.LabelVideoRequest.Feature = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a labeling task for video. The type of video - labeling task is configured by feature in the request. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.LabelVideoRequest`): - The request object. Request message for LabelVideo. - parent (:class:`str`): - Required. Name of the dataset to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - basic_config (:class:`google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig`): - Required. Basic human annotation - config. - - This corresponds to the ``basic_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - feature (:class:`google.cloud.datalabeling_v1beta1.types.LabelVideoRequest.Feature`): - Required. The type of video labeling - task. - - This corresponds to the ``feature`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each - labeling task will generate an AnnotatedDataset under - the Dataset that the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, basic_config, feature]) - if request is 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 = data_labeling_service.LabelVideoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if basic_config is not None: - request.basic_config = basic_config - if feature is not None: - request.feature = feature - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.label_video, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - dataset.AnnotatedDataset, - metadata_type=operations.LabelOperationMetadata, - ) - - # Done; return the response. - return response - - async def label_text(self, - request: data_labeling_service.LabelTextRequest = None, - *, - parent: str = None, - basic_config: human_annotation_config.HumanAnnotationConfig = None, - feature: data_labeling_service.LabelTextRequest.Feature = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a labeling task for text. The type of text - labeling task is configured by feature in the request. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.LabelTextRequest`): - The request object. Request message for LabelText. - parent (:class:`str`): - Required. Name of the data set to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - basic_config (:class:`google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig`): - Required. Basic human annotation - config. - - This corresponds to the ``basic_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - feature (:class:`google.cloud.datalabeling_v1beta1.types.LabelTextRequest.Feature`): - Required. The type of text labeling - task. - - This corresponds to the ``feature`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each - labeling task will generate an AnnotatedDataset under - the Dataset that the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, basic_config, feature]) - if request is 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 = data_labeling_service.LabelTextRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if basic_config is not None: - request.basic_config = basic_config - if feature is not None: - request.feature = feature - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.label_text, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - dataset.AnnotatedDataset, - metadata_type=operations.LabelOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_example(self, - request: data_labeling_service.GetExampleRequest = None, - *, - name: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.Example: - r"""Gets an example by resource name, including both data - and annotation. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetExampleRequest`): - The request object. Request message for GetExample - name (:class:`str`): - Required. Name of example, format: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id}/examples/{example_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. An expression for filtering Examples. Filter - by annotation_spec.display_name is supported. Format - "annotation_spec.display_name = {display_name}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.Example: - An Example is a piece of data and its - annotation. For example, an image with - label "house". - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.GetExampleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if filter is not None: - request.filter = filter - - # 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_example, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_examples(self, - request: data_labeling_service.ListExamplesRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExamplesAsyncPager: - r"""Lists examples in an annotated dataset. Pagination is - supported. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ListExamplesRequest`): - The request object. Request message for ListExamples. - parent (:class:`str`): - Required. Example resource parent. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. An expression for filtering Examples. For - annotated datasets that have annotation spec set, filter - by annotation_spec.display_name is supported. Format - "annotation_spec.display_name = {display_name}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListExamplesAsyncPager: - Results of listing Examples in and - annotated dataset. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.ListExamplesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_examples, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListExamplesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_annotation_spec_set(self, - request: data_labeling_service.CreateAnnotationSpecSetRequest = None, - *, - parent: str = None, - annotation_spec_set: gcd_annotation_spec_set.AnnotationSpecSet = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_annotation_spec_set.AnnotationSpecSet: - r"""Creates an annotation spec set by providing a set of - labels. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.CreateAnnotationSpecSetRequest`): - The request object. Request message for - CreateAnnotationSpecSet. - parent (:class:`str`): - Required. AnnotationSpecSet resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - annotation_spec_set (:class:`google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet`): - Required. Annotation spec set to create. Annotation - specs must be included. Only one annotation spec will be - accepted for annotation specs with same display_name. - - This corresponds to the ``annotation_spec_set`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotationSpecSet: - An AnnotationSpecSet is a collection - of label definitions. For example, in - image classification tasks, you define a - set of possible labels for images as an - AnnotationSpecSet. An AnnotationSpecSet - is immutable upon creation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, annotation_spec_set]) - if request is 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 = data_labeling_service.CreateAnnotationSpecSetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if annotation_spec_set is not None: - request.annotation_spec_set = annotation_spec_set - - # 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_annotation_spec_set, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_annotation_spec_set(self, - request: data_labeling_service.GetAnnotationSpecSetRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> annotation_spec_set.AnnotationSpecSet: - r"""Gets an annotation spec set by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetAnnotationSpecSetRequest`): - The request object. Request message for - GetAnnotationSpecSet. - name (:class:`str`): - Required. AnnotationSpecSet resource name, format: - projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} - - 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.datalabeling_v1beta1.types.AnnotationSpecSet: - An AnnotationSpecSet is a collection - of label definitions. For example, in - image classification tasks, you define a - set of possible labels for images as an - AnnotationSpecSet. An AnnotationSpecSet - is immutable upon creation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.GetAnnotationSpecSetRequest(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_annotation_spec_set, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_annotation_spec_sets(self, - request: data_labeling_service.ListAnnotationSpecSetsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnnotationSpecSetsAsyncPager: - r"""Lists annotation spec sets for a project. Pagination - is supported. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest`): - The request object. Request message for - ListAnnotationSpecSets. - parent (:class:`str`): - Required. Parent of AnnotationSpecSet resource, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotationSpecSetsAsyncPager: - Results of listing annotation spec - set under a project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.ListAnnotationSpecSetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_annotation_spec_sets, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAnnotationSpecSetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_annotation_spec_set(self, - request: data_labeling_service.DeleteAnnotationSpecSetRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an annotation spec set by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteAnnotationSpecSetRequest`): - The request object. Request message for - DeleteAnnotationSpecSet. - name (:class:`str`): - Required. AnnotationSpec resource name, format: - ``projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}``. - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.DeleteAnnotationSpecSetRequest(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_annotation_spec_set, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_instruction(self, - request: data_labeling_service.CreateInstructionRequest = None, - *, - parent: str = None, - instruction: gcd_instruction.Instruction = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates an instruction for how data should be - labeled. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.CreateInstructionRequest`): - The request object. Request message for - CreateInstruction. - parent (:class:`str`): - Required. Instruction resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - instruction (:class:`google.cloud.datalabeling_v1beta1.types.Instruction`): - Required. Instruction of how to - perform the labeling task. - - This corresponds to the ``instruction`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.Instruction` Instruction of how to perform the labeling task for human operators. - Currently only PDF instruction is supported. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, instruction]) - if request is 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 = data_labeling_service.CreateInstructionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if instruction is not None: - request.instruction = instruction - - # 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_instruction, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_instruction.Instruction, - metadata_type=operations.CreateInstructionMetadata, - ) - - # Done; return the response. - return response - - async def get_instruction(self, - request: data_labeling_service.GetInstructionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instruction.Instruction: - r"""Gets an instruction by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetInstructionRequest`): - The request object. Request message for GetInstruction. - name (:class:`str`): - Required. Instruction resource name, format: - projects/{project_id}/instructions/{instruction_id} - - 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.datalabeling_v1beta1.types.Instruction: - Instruction of how to perform the - labeling task for human operators. - Currently only PDF instruction is - supported. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.GetInstructionRequest(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_instruction, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_instructions(self, - request: data_labeling_service.ListInstructionsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInstructionsAsyncPager: - r"""Lists instructions for a project. Pagination is - supported. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsRequest`): - The request object. Request message for - ListInstructions. - parent (:class:`str`): - Required. Instruction resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListInstructionsAsyncPager: - Results of listing instructions under - a project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.ListInstructionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_instructions, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListInstructionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_instruction(self, - request: data_labeling_service.DeleteInstructionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an instruction object by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteInstructionRequest`): - The request object. Request message for - DeleteInstruction. - name (:class:`str`): - Required. Instruction resource name, format: - projects/{project_id}/instructions/{instruction_id} - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.DeleteInstructionRequest(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_instruction, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_evaluation(self, - request: data_labeling_service.GetEvaluationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation.Evaluation: - r"""Gets an evaluation by resource name (to search, use - [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetEvaluationRequest`): - The request object. Request message for GetEvaluation. - name (:class:`str`): - Required. Name of the evaluation. Format: - - "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' - - 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.datalabeling_v1beta1.types.Evaluation: - Describes an evaluation between a machine learning model's predictions and - ground truth labels. Created when an - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] - runs successfully. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_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_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_evaluations(self, - request: data_labeling_service.SearchEvaluationsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchEvaluationsAsyncPager: - r"""Searches - [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] - within a project. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsRequest`): - The request object. Request message for - SearchEvaluation. - parent (:class:`str`): - Required. Evaluation search parent (project ID). Format: - "projects/{project_id}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. To search evaluations, you can filter by the - following: - - - evaluation\_job.evaluation_job_id (the last part of - [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) - - evaluation\_job.model_id (the {model_name} portion of - [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) - - evaluation\_job.evaluation_job_run_time_start - (Minimum threshold for the - [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] - that created the evaluation) - - evaluation\_job.evaluation_job_run_time_end (Maximum - threshold for the - [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] - that created the evaluation) - - evaluation\_job.job_state - ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) - - annotation\_spec.display_name (the Evaluation - contains a metric for the annotation spec with this - [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) - - To filter by multiple critiera, use the ``AND`` operator - or the ``OR`` operator. The following examples shows a - string that filters by several critiera: - - "evaluation\ *job.evaluation_job_id = - {evaluation_job_id} AND evaluation*\ job.model_id = - {model_name} AND - evaluation\ *job.evaluation_job_run_time_start = - {timestamp_1} AND - evaluation*\ job.evaluation_job_run_time_end = - {timestamp_2} AND annotation\_spec.display_name = - {display_name}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchEvaluationsAsyncPager: - Results of searching evaluations. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.SearchEvaluationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_evaluations, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchEvaluationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_example_comparisons(self, - request: data_labeling_service.SearchExampleComparisonsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchExampleComparisonsAsyncPager: - r"""Searches example comparisons from an evaluation. The - return format is a list of example comparisons that show - ground truth and prediction(s) for a single input. - Search by providing an evaluation ID. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsRequest`): - The request object. Request message of - SearchExampleComparisons. - parent (:class:`str`): - Required. Name of the - [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] - resource to search for example comparisons from. Format: - - "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}" - - 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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchExampleComparisonsAsyncPager: - Results of searching example - comparisons. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.SearchExampleComparisonsRequest(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.search_example_comparisons, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchExampleComparisonsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_evaluation_job(self, - request: data_labeling_service.CreateEvaluationJobRequest = None, - *, - parent: str = None, - job: evaluation_job.EvaluationJob = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation_job.EvaluationJob: - r"""Creates an evaluation job. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.CreateEvaluationJobRequest`): - The request object. Request message for - CreateEvaluationJob. - parent (:class:`str`): - Required. Evaluation job resource parent. Format: - "projects/{project_id}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - job (:class:`google.cloud.datalabeling_v1beta1.types.EvaluationJob`): - Required. The evaluation job to - create. - - This corresponds to the ``job`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.EvaluationJob: - Defines an evaluation job that runs periodically to generate - [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. - [Creating an evaluation - job](/ml-engine/docs/continuous-evaluation/create-job) - is the starting point for using continuous - evaluation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, job]) - if request is 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 = data_labeling_service.CreateEvaluationJobRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if job is not None: - request.job = job - - # 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_evaluation_job, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_evaluation_job(self, - request: data_labeling_service.UpdateEvaluationJobRequest = None, - *, - evaluation_job: gcd_evaluation_job.EvaluationJob = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_evaluation_job.EvaluationJob: - r"""Updates an evaluation job. You can only update certain fields of - the job's - [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: - ``humanAnnotationConfig.instruction``, ``exampleCount``, and - ``exampleSamplePercentage``. - - If you want to change any other aspect of the evaluation job, - you must delete the job and create a new one. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.UpdateEvaluationJobRequest`): - The request object. Request message for - UpdateEvaluationJob. - evaluation_job (:class:`google.cloud.datalabeling_v1beta1.types.EvaluationJob`): - Required. Evaluation job that is - going to be updated. - - This corresponds to the ``evaluation_job`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Mask for which fields to update. You can only - provide the following fields: - - - ``evaluationJobConfig.humanAnnotationConfig.instruction`` - - ``evaluationJobConfig.exampleCount`` - - ``evaluationJobConfig.exampleSamplePercentage`` - - You can provide more than one of these fields by - separating them with commas. - - 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.datalabeling_v1beta1.types.EvaluationJob: - Defines an evaluation job that runs periodically to generate - [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. - [Creating an evaluation - job](/ml-engine/docs/continuous-evaluation/create-job) - is the starting point for using continuous - evaluation. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([evaluation_job, 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 = data_labeling_service.UpdateEvaluationJobRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if evaluation_job is not None: - request.evaluation_job = evaluation_job - 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_evaluation_job, - default_timeout=30.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(( - ("evaluation_job.name", request.evaluation_job.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_evaluation_job(self, - request: data_labeling_service.GetEvaluationJobRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation_job.EvaluationJob: - r"""Gets an evaluation job by resource name. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.GetEvaluationJobRequest`): - The request object. Request message for - GetEvaluationJob. - name (:class:`str`): - Required. Name of the evaluation job. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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.datalabeling_v1beta1.types.EvaluationJob: - Defines an evaluation job that runs periodically to generate - [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. - [Creating an evaluation - job](/ml-engine/docs/continuous-evaluation/create-job) - is the starting point for using continuous - evaluation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.GetEvaluationJobRequest(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_job, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def pause_evaluation_job(self, - request: data_labeling_service.PauseEvaluationJobRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Pauses an evaluation job. Pausing an evaluation job that is - already in a ``PAUSED`` state is a no-op. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.PauseEvaluationJobRequest`): - The request object. Request message for - PauseEvaluationJob. - name (:class:`str`): - Required. Name of the evaluation job that is going to be - paused. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.PauseEvaluationJobRequest(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.pause_evaluation_job, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def resume_evaluation_job(self, - request: data_labeling_service.ResumeEvaluationJobRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Resumes a paused evaluation job. A deleted evaluation - job can't be resumed. Resuming a running or scheduled - evaluation job is a no-op. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ResumeEvaluationJobRequest`): - The request object. Request message ResumeEvaluationJob. - name (:class:`str`): - Required. Name of the evaluation job that is going to be - resumed. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.ResumeEvaluationJobRequest(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.resume_evaluation_job, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def delete_evaluation_job(self, - request: data_labeling_service.DeleteEvaluationJobRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Stops and deletes an evaluation job. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.DeleteEvaluationJobRequest`): - The request object. Request message DeleteEvaluationJob. - name (:class:`str`): - Required. Name of the evaluation job that is going to be - deleted. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = data_labeling_service.DeleteEvaluationJobRequest(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_evaluation_job, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_evaluation_jobs(self, - request: data_labeling_service.ListEvaluationJobsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEvaluationJobsAsyncPager: - r"""Lists all evaluation jobs within a project with - possible filters. Pagination is supported. - - Args: - request (:class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsRequest`): - The request object. Request message for - ListEvaluationJobs. - parent (:class:`str`): - Required. Evaluation job resource parent. Format: - "projects/{project_id}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. You can filter the jobs to list by model_id - (also known as model_name, as described in - [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) - or by evaluation job state (as described in - [EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]). - To filter by both criteria, use the ``AND`` operator or - the ``OR`` operator. For example, you can use the - following string for your filter: - "evaluation\ *job.model_id = {model_name} AND - evaluation*\ job.state = {evaluation_job_state}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListEvaluationJobsAsyncPager: - Results for listing evaluation jobs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 = data_labeling_service.ListEvaluationJobsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_evaluation_jobs, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEvaluationJobsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datalabeling", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataLabelingServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py deleted file mode 100644 index 00f6ba7..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py +++ /dev/null @@ -1,3451 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.datalabeling_v1beta1.services.data_labeling_service import pagers -from google.cloud.datalabeling_v1beta1.types import annotation -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import data_labeling_service -from google.cloud.datalabeling_v1beta1.types import data_payloads -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job -from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job -from google.cloud.datalabeling_v1beta1.types import human_annotation_config -from google.cloud.datalabeling_v1beta1.types import instruction -from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction -from google.cloud.datalabeling_v1beta1.types import operations -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DataLabelingServiceGrpcTransport -from .transports.grpc_asyncio import DataLabelingServiceGrpcAsyncIOTransport - - -class DataLabelingServiceClientMeta(type): - """Metaclass for the DataLabelingService 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[DataLabelingServiceTransport]] - _transport_registry["grpc"] = DataLabelingServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DataLabelingServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[DataLabelingServiceTransport]: - """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 DataLabelingServiceClient(metaclass=DataLabelingServiceClientMeta): - """Service for the AI Platform Data Labeling API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "datalabeling.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DataLabelingServiceClient: 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: - DataLabelingServiceClient: 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) -> DataLabelingServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DataLabelingServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def annotated_dataset_path(project: str,dataset: str,annotated_dataset: str,) -> str: - """Returns a fully-qualified annotated_dataset string.""" - return "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, ) - - @staticmethod - def parse_annotated_dataset_path(path: str) -> Dict[str,str]: - """Parses a annotated_dataset path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)/annotatedDatasets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def annotation_spec_set_path(project: str,annotation_spec_set: str,) -> str: - """Returns a fully-qualified annotation_spec_set string.""" - return "projects/{project}/annotationSpecSets/{annotation_spec_set}".format(project=project, annotation_spec_set=annotation_spec_set, ) - - @staticmethod - def parse_annotation_spec_set_path(path: str) -> Dict[str,str]: - """Parses a annotation_spec_set path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/annotationSpecSets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def data_item_path(project: str,dataset: str,data_item: str,) -> str: - """Returns a fully-qualified data_item string.""" - return "projects/{project}/datasets/{dataset}/dataItems/{data_item}".format(project=project, dataset=dataset, data_item=data_item, ) - - @staticmethod - def parse_data_item_path(path: str) -> Dict[str,str]: - """Parses a data_item path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)/dataItems/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def dataset_path(project: str,dataset: str,) -> str: - """Returns a fully-qualified dataset string.""" - return "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) - - @staticmethod - def parse_dataset_path(path: str) -> Dict[str,str]: - """Parses a dataset path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def evaluation_path(project: str,dataset: str,evaluation: str,) -> str: - """Returns a fully-qualified evaluation string.""" - return "projects/{project}/datasets/{dataset}/evaluations/{evaluation}".format(project=project, dataset=dataset, 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.+?)/datasets/(?P.+?)/evaluations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def evaluation_job_path(project: str,evaluation_job: str,) -> str: - """Returns a fully-qualified evaluation_job string.""" - return "projects/{project}/evaluationJobs/{evaluation_job}".format(project=project, evaluation_job=evaluation_job, ) - - @staticmethod - def parse_evaluation_job_path(path: str) -> Dict[str,str]: - """Parses a evaluation_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/evaluationJobs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def example_path(project: str,dataset: str,annotated_dataset: str,example: str,) -> str: - """Returns a fully-qualified example string.""" - return "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, ) - - @staticmethod - def parse_example_path(path: str) -> Dict[str,str]: - """Parses a example path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)/annotatedDatasets/(?P.+?)/examples/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def instruction_path(project: str,instruction: str,) -> str: - """Returns a fully-qualified instruction string.""" - return "projects/{project}/instructions/{instruction}".format(project=project, instruction=instruction, ) - - @staticmethod - def parse_instruction_path(path: str) -> Dict[str,str]: - """Parses a instruction path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/instructions/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DataLabelingServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data labeling 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, DataLabelingServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DataLabelingServiceTransport): - # transport is a DataLabelingServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_dataset(self, - request: Union[data_labeling_service.CreateDatasetRequest, dict] = None, - *, - parent: str = None, - dataset: gcd_dataset.Dataset = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_dataset.Dataset: - r"""Creates dataset. If success return a Dataset - resource. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.CreateDatasetRequest, dict]): - The request object. Request message for CreateDataset. - parent (str): - Required. Dataset resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - dataset (google.cloud.datalabeling_v1beta1.types.Dataset): - Required. The dataset to be created. - 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.datalabeling_v1beta1.types.Dataset: - Dataset is the resource to hold your - data. You can request multiple labeling - tasks for a dataset while each one will - generate an AnnotatedDataset. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, 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 data_labeling_service.CreateDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.CreateDatasetRequest): - request = data_labeling_service.CreateDatasetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - 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.create_dataset] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_dataset(self, - request: Union[data_labeling_service.GetDatasetRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.Dataset: - r"""Gets dataset by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetDatasetRequest, dict]): - The request object. Request message for GetDataSet. - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - 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.datalabeling_v1beta1.types.Dataset: - Dataset is the resource to hold your - data. You can request multiple labeling - tasks for a dataset while each one will - generate an AnnotatedDataset. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.GetDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetDatasetRequest): - request = data_labeling_service.GetDatasetRequest(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] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_datasets(self, - request: Union[data_labeling_service.ListDatasetsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDatasetsPager: - r"""Lists datasets under a project. Pagination is - supported. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ListDatasetsRequest, dict]): - The request object. Request message for ListDataset. - parent (str): - Required. Dataset resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. Filter on dataset is not - supported at this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDatasetsPager: - Results of listing datasets within a - project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.ListDatasetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ListDatasetsRequest): - request = data_labeling_service.ListDatasetsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_datasets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDatasetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_dataset(self, - request: Union[data_labeling_service.DeleteDatasetRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a dataset by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.DeleteDatasetRequest, dict]): - The request object. Request message for DeleteDataset. - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.DeleteDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.DeleteDatasetRequest): - request = data_labeling_service.DeleteDatasetRequest(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_dataset] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_data(self, - request: Union[data_labeling_service.ImportDataRequest, dict] = None, - *, - name: str = None, - input_config: dataset.InputConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports data into dataset based on source locations - defined in request. It can be called multiple times for - the same dataset. Each dataset can only have one long - running operation running on it. For example, no - labeling task (also long running operation) can be - started while importing is still ongoing. Vice versa. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ImportDataRequest, dict]): - The request object. Request message for ImportData API. - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (google.cloud.datalabeling_v1beta1.types.InputConfig): - Required. Specify the input source of - the data. - - This corresponds to the ``input_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.datalabeling_v1beta1.types.ImportDataOperationResponse` - Response used for ImportData longrunning operation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, input_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 data_labeling_service.ImportDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ImportDataRequest): - request = data_labeling_service.ImportDataRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if input_config is not None: - request.input_config = input_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - operations.ImportDataOperationResponse, - metadata_type=operations.ImportDataOperationMetadata, - ) - - # Done; return the response. - return response - - def export_data(self, - request: Union[data_labeling_service.ExportDataRequest, dict] = None, - *, - name: str = None, - annotated_dataset: str = None, - filter: str = None, - output_config: dataset.OutputConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports data and annotations from dataset. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ExportDataRequest, dict]): - The request object. Request message for ExportData API. - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - annotated_dataset (str): - Required. Annotated dataset resource name. DataItem in - Dataset and their annotations in specified annotated - dataset will be exported. It's in format of - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - - This corresponds to the ``annotated_dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - output_config (google.cloud.datalabeling_v1beta1.types.OutputConfig): - Required. Specify the output - destination. - - This corresponds to the ``output_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.datalabeling_v1beta1.types.ExportDataOperationResponse` - Response used for ExportDataset longrunning operation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, annotated_dataset, filter, output_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 data_labeling_service.ExportDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ExportDataRequest): - request = data_labeling_service.ExportDataRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if annotated_dataset is not None: - request.annotated_dataset = annotated_dataset - if filter is not None: - request.filter = filter - if output_config is not None: - request.output_config = output_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - operations.ExportDataOperationResponse, - metadata_type=operations.ExportDataOperationMetadata, - ) - - # Done; return the response. - return response - - def get_data_item(self, - request: Union[data_labeling_service.GetDataItemRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.DataItem: - r"""Gets a data item in a dataset by resource name. This - API can be called after data are imported into dataset. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetDataItemRequest, dict]): - The request object. Request message for GetDataItem. - name (str): - Required. The name of the data item to get, format: - projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} - - 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.datalabeling_v1beta1.types.DataItem: - DataItem is a piece of data, without - annotation. For example, an image. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.GetDataItemRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetDataItemRequest): - request = data_labeling_service.GetDataItemRequest(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_data_item] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_data_items(self, - request: Union[data_labeling_service.ListDataItemsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataItemsPager: - r"""Lists data items in a dataset. This API can be called - after data are imported into dataset. Pagination is - supported. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ListDataItemsRequest, dict]): - The request object. Request message for ListDataItems. - parent (str): - Required. Name of the dataset to list data items, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListDataItemsPager: - Results of listing data items in a - dataset. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.ListDataItemsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ListDataItemsRequest): - request = data_labeling_service.ListDataItemsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_data_items] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDataItemsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_annotated_dataset(self, - request: Union[data_labeling_service.GetAnnotatedDatasetRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.AnnotatedDataset: - r"""Gets an annotated dataset by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetAnnotatedDatasetRequest, dict]): - The request object. Request message for - GetAnnotatedDataset. - name (str): - Required. Name of the annotated dataset to get, format: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - - 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.datalabeling_v1beta1.types.AnnotatedDataset: - AnnotatedDataset is a set holding - annotations for data in a Dataset. Each - labeling task will generate an - AnnotatedDataset under the Dataset that - the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.GetAnnotatedDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetAnnotatedDatasetRequest): - request = data_labeling_service.GetAnnotatedDatasetRequest(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_annotated_dataset] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_annotated_datasets(self, - request: Union[data_labeling_service.ListAnnotatedDatasetsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnnotatedDatasetsPager: - r"""Lists annotated datasets for a dataset. Pagination is - supported. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest, dict]): - The request object. Request message for - ListAnnotatedDatasets. - parent (str): - Required. Name of the dataset to list annotated - datasets, format: - projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotatedDatasetsPager: - Results of listing annotated datasets - for a dataset. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.ListAnnotatedDatasetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ListAnnotatedDatasetsRequest): - request = data_labeling_service.ListAnnotatedDatasetsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_annotated_datasets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAnnotatedDatasetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_annotated_dataset(self, - request: Union[data_labeling_service.DeleteAnnotatedDatasetRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an annotated dataset by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.DeleteAnnotatedDatasetRequest, dict]): - The request object. Request message for - DeleteAnnotatedDataset. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a data_labeling_service.DeleteAnnotatedDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.DeleteAnnotatedDatasetRequest): - request = data_labeling_service.DeleteAnnotatedDatasetRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_annotated_dataset] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def label_image(self, - request: Union[data_labeling_service.LabelImageRequest, dict] = None, - *, - parent: str = None, - basic_config: human_annotation_config.HumanAnnotationConfig = None, - feature: data_labeling_service.LabelImageRequest.Feature = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a labeling task for image. The type of image - labeling task is configured by feature in the request. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.LabelImageRequest, dict]): - The request object. Request message for starting an - image labeling task. - parent (str): - Required. Name of the dataset to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Required. Basic human annotation - config. - - This corresponds to the ``basic_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - feature (google.cloud.datalabeling_v1beta1.types.LabelImageRequest.Feature): - Required. The type of image labeling - task. - - This corresponds to the ``feature`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each - labeling task will generate an AnnotatedDataset under - the Dataset that the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, basic_config, feature]) - if request is 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 data_labeling_service.LabelImageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.LabelImageRequest): - request = data_labeling_service.LabelImageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if basic_config is not None: - request.basic_config = basic_config - if feature is not None: - request.feature = feature - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.label_image] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - dataset.AnnotatedDataset, - metadata_type=operations.LabelOperationMetadata, - ) - - # Done; return the response. - return response - - def label_video(self, - request: Union[data_labeling_service.LabelVideoRequest, dict] = None, - *, - parent: str = None, - basic_config: human_annotation_config.HumanAnnotationConfig = None, - feature: data_labeling_service.LabelVideoRequest.Feature = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a labeling task for video. The type of video - labeling task is configured by feature in the request. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.LabelVideoRequest, dict]): - The request object. Request message for LabelVideo. - parent (str): - Required. Name of the dataset to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Required. Basic human annotation - config. - - This corresponds to the ``basic_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - feature (google.cloud.datalabeling_v1beta1.types.LabelVideoRequest.Feature): - Required. The type of video labeling - task. - - This corresponds to the ``feature`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each - labeling task will generate an AnnotatedDataset under - the Dataset that the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, basic_config, feature]) - if request is 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 data_labeling_service.LabelVideoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.LabelVideoRequest): - request = data_labeling_service.LabelVideoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if basic_config is not None: - request.basic_config = basic_config - if feature is not None: - request.feature = feature - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.label_video] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - dataset.AnnotatedDataset, - metadata_type=operations.LabelOperationMetadata, - ) - - # Done; return the response. - return response - - def label_text(self, - request: Union[data_labeling_service.LabelTextRequest, dict] = None, - *, - parent: str = None, - basic_config: human_annotation_config.HumanAnnotationConfig = None, - feature: data_labeling_service.LabelTextRequest.Feature = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a labeling task for text. The type of text - labeling task is configured by feature in the request. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.LabelTextRequest, dict]): - The request object. Request message for LabelText. - parent (str): - Required. Name of the data set to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Required. Basic human annotation - config. - - This corresponds to the ``basic_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - feature (google.cloud.datalabeling_v1beta1.types.LabelTextRequest.Feature): - Required. The type of text labeling - task. - - This corresponds to the ``feature`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotatedDataset` AnnotatedDataset is a set holding annotations for data in a Dataset. Each - labeling task will generate an AnnotatedDataset under - the Dataset that the task is requested for. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, basic_config, feature]) - if request is 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 data_labeling_service.LabelTextRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.LabelTextRequest): - request = data_labeling_service.LabelTextRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if basic_config is not None: - request.basic_config = basic_config - if feature is not None: - request.feature = feature - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.label_text] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - dataset.AnnotatedDataset, - metadata_type=operations.LabelOperationMetadata, - ) - - # Done; return the response. - return response - - def get_example(self, - request: Union[data_labeling_service.GetExampleRequest, dict] = None, - *, - name: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dataset.Example: - r"""Gets an example by resource name, including both data - and annotation. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetExampleRequest, dict]): - The request object. Request message for GetExample - name (str): - Required. Name of example, format: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id}/examples/{example_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. An expression for filtering Examples. Filter - by annotation_spec.display_name is supported. Format - "annotation_spec.display_name = {display_name}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.Example: - An Example is a piece of data and its - annotation. For example, an image with - label "house". - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.GetExampleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetExampleRequest): - request = data_labeling_service.GetExampleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_example] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_examples(self, - request: Union[data_labeling_service.ListExamplesRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExamplesPager: - r"""Lists examples in an annotated dataset. Pagination is - supported. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ListExamplesRequest, dict]): - The request object. Request message for ListExamples. - parent (str): - Required. Example resource parent. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. An expression for filtering Examples. For - annotated datasets that have annotation spec set, filter - by annotation_spec.display_name is supported. Format - "annotation_spec.display_name = {display_name}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListExamplesPager: - Results of listing Examples in and - annotated dataset. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.ListExamplesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ListExamplesRequest): - request = data_labeling_service.ListExamplesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_examples] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListExamplesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_annotation_spec_set(self, - request: Union[data_labeling_service.CreateAnnotationSpecSetRequest, dict] = None, - *, - parent: str = None, - annotation_spec_set: gcd_annotation_spec_set.AnnotationSpecSet = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_annotation_spec_set.AnnotationSpecSet: - r"""Creates an annotation spec set by providing a set of - labels. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.CreateAnnotationSpecSetRequest, dict]): - The request object. Request message for - CreateAnnotationSpecSet. - parent (str): - Required. AnnotationSpecSet resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - annotation_spec_set (google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet): - Required. Annotation spec set to create. Annotation - specs must be included. Only one annotation spec will be - accepted for annotation specs with same display_name. - - This corresponds to the ``annotation_spec_set`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.AnnotationSpecSet: - An AnnotationSpecSet is a collection - of label definitions. For example, in - image classification tasks, you define a - set of possible labels for images as an - AnnotationSpecSet. An AnnotationSpecSet - is immutable upon creation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, annotation_spec_set]) - if request is 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 data_labeling_service.CreateAnnotationSpecSetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.CreateAnnotationSpecSetRequest): - request = data_labeling_service.CreateAnnotationSpecSetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if annotation_spec_set is not None: - request.annotation_spec_set = annotation_spec_set - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_annotation_spec_set] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_annotation_spec_set(self, - request: Union[data_labeling_service.GetAnnotationSpecSetRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> annotation_spec_set.AnnotationSpecSet: - r"""Gets an annotation spec set by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetAnnotationSpecSetRequest, dict]): - The request object. Request message for - GetAnnotationSpecSet. - name (str): - Required. AnnotationSpecSet resource name, format: - projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} - - 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.datalabeling_v1beta1.types.AnnotationSpecSet: - An AnnotationSpecSet is a collection - of label definitions. For example, in - image classification tasks, you define a - set of possible labels for images as an - AnnotationSpecSet. An AnnotationSpecSet - is immutable upon creation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.GetAnnotationSpecSetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetAnnotationSpecSetRequest): - request = data_labeling_service.GetAnnotationSpecSetRequest(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_annotation_spec_set] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_annotation_spec_sets(self, - request: Union[data_labeling_service.ListAnnotationSpecSetsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnnotationSpecSetsPager: - r"""Lists annotation spec sets for a project. Pagination - is supported. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest, dict]): - The request object. Request message for - ListAnnotationSpecSets. - parent (str): - Required. Parent of AnnotationSpecSet resource, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListAnnotationSpecSetsPager: - Results of listing annotation spec - set under a project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.ListAnnotationSpecSetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ListAnnotationSpecSetsRequest): - request = data_labeling_service.ListAnnotationSpecSetsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_annotation_spec_sets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAnnotationSpecSetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_annotation_spec_set(self, - request: Union[data_labeling_service.DeleteAnnotationSpecSetRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an annotation spec set by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.DeleteAnnotationSpecSetRequest, dict]): - The request object. Request message for - DeleteAnnotationSpecSet. - name (str): - Required. AnnotationSpec resource name, format: - ``projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}``. - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.DeleteAnnotationSpecSetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.DeleteAnnotationSpecSetRequest): - request = data_labeling_service.DeleteAnnotationSpecSetRequest(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_annotation_spec_set] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def create_instruction(self, - request: Union[data_labeling_service.CreateInstructionRequest, dict] = None, - *, - parent: str = None, - instruction: gcd_instruction.Instruction = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates an instruction for how data should be - labeled. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.CreateInstructionRequest, dict]): - The request object. Request message for - CreateInstruction. - parent (str): - Required. Instruction resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - instruction (google.cloud.datalabeling_v1beta1.types.Instruction): - Required. Instruction of how to - perform the labeling task. - - This corresponds to the ``instruction`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.Instruction` Instruction of how to perform the labeling task for human operators. - Currently only PDF instruction is supported. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, instruction]) - if request is 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 data_labeling_service.CreateInstructionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.CreateInstructionRequest): - request = data_labeling_service.CreateInstructionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if instruction is not None: - request.instruction = instruction - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_instruction] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_instruction.Instruction, - metadata_type=operations.CreateInstructionMetadata, - ) - - # Done; return the response. - return response - - def get_instruction(self, - request: Union[data_labeling_service.GetInstructionRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instruction.Instruction: - r"""Gets an instruction by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetInstructionRequest, dict]): - The request object. Request message for GetInstruction. - name (str): - Required. Instruction resource name, format: - projects/{project_id}/instructions/{instruction_id} - - 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.datalabeling_v1beta1.types.Instruction: - Instruction of how to perform the - labeling task for human operators. - Currently only PDF instruction is - supported. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.GetInstructionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetInstructionRequest): - request = data_labeling_service.GetInstructionRequest(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_instruction] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_instructions(self, - request: Union[data_labeling_service.ListInstructionsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInstructionsPager: - r"""Lists instructions for a project. Pagination is - supported. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ListInstructionsRequest, dict]): - The request object. Request message for - ListInstructions. - parent (str): - Required. Instruction resource parent, format: - projects/{project_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. Filter is not supported at - this moment. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListInstructionsPager: - Results of listing instructions under - a project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.ListInstructionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ListInstructionsRequest): - request = data_labeling_service.ListInstructionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_instructions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListInstructionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_instruction(self, - request: Union[data_labeling_service.DeleteInstructionRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an instruction object by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.DeleteInstructionRequest, dict]): - The request object. Request message for - DeleteInstruction. - name (str): - Required. Instruction resource name, format: - projects/{project_id}/instructions/{instruction_id} - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.DeleteInstructionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.DeleteInstructionRequest): - request = data_labeling_service.DeleteInstructionRequest(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_instruction] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_evaluation(self, - request: Union[data_labeling_service.GetEvaluationRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation.Evaluation: - r"""Gets an evaluation by resource name (to search, use - [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetEvaluationRequest, dict]): - The request object. Request message for GetEvaluation. - name (str): - Required. Name of the evaluation. Format: - - "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' - - 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.datalabeling_v1beta1.types.Evaluation: - Describes an evaluation between a machine learning model's predictions and - ground truth labels. Created when an - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] - runs successfully. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.GetEvaluationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetEvaluationRequest): - request = data_labeling_service.GetEvaluationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_evaluation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_evaluations(self, - request: Union[data_labeling_service.SearchEvaluationsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchEvaluationsPager: - r"""Searches - [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] - within a project. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.SearchEvaluationsRequest, dict]): - The request object. Request message for - SearchEvaluation. - parent (str): - Required. Evaluation search parent (project ID). Format: - "projects/{project_id}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. To search evaluations, you can filter by the - following: - - - evaluation\_job.evaluation_job_id (the last part of - [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) - - evaluation\_job.model_id (the {model_name} portion of - [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) - - evaluation\_job.evaluation_job_run_time_start - (Minimum threshold for the - [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] - that created the evaluation) - - evaluation\_job.evaluation_job_run_time_end (Maximum - threshold for the - [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] - that created the evaluation) - - evaluation\_job.job_state - ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) - - annotation\_spec.display_name (the Evaluation - contains a metric for the annotation spec with this - [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) - - To filter by multiple critiera, use the ``AND`` operator - or the ``OR`` operator. The following examples shows a - string that filters by several critiera: - - "evaluation\ *job.evaluation_job_id = - {evaluation_job_id} AND evaluation*\ job.model_id = - {model_name} AND - evaluation\ *job.evaluation_job_run_time_start = - {timestamp_1} AND - evaluation*\ job.evaluation_job_run_time_end = - {timestamp_2} AND annotation\_spec.display_name = - {display_name}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchEvaluationsPager: - Results of searching evaluations. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.SearchEvaluationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.SearchEvaluationsRequest): - request = data_labeling_service.SearchEvaluationsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_evaluations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchEvaluationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_example_comparisons(self, - request: Union[data_labeling_service.SearchExampleComparisonsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchExampleComparisonsPager: - r"""Searches example comparisons from an evaluation. The - return format is a list of example comparisons that show - ground truth and prediction(s) for a single input. - Search by providing an evaluation ID. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsRequest, dict]): - The request object. Request message of - SearchExampleComparisons. - parent (str): - Required. Name of the - [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] - resource to search for example comparisons from. Format: - - "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}" - - 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.datalabeling_v1beta1.services.data_labeling_service.pagers.SearchExampleComparisonsPager: - Results of searching example - comparisons. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.SearchExampleComparisonsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.SearchExampleComparisonsRequest): - request = data_labeling_service.SearchExampleComparisonsRequest(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.search_example_comparisons] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchExampleComparisonsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_evaluation_job(self, - request: Union[data_labeling_service.CreateEvaluationJobRequest, dict] = None, - *, - parent: str = None, - job: evaluation_job.EvaluationJob = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation_job.EvaluationJob: - r"""Creates an evaluation job. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.CreateEvaluationJobRequest, dict]): - The request object. Request message for - CreateEvaluationJob. - parent (str): - Required. Evaluation job resource parent. Format: - "projects/{project_id}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): - Required. The evaluation job to - create. - - This corresponds to the ``job`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.types.EvaluationJob: - Defines an evaluation job that runs periodically to generate - [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. - [Creating an evaluation - job](/ml-engine/docs/continuous-evaluation/create-job) - is the starting point for using continuous - evaluation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, job]) - if request is 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 data_labeling_service.CreateEvaluationJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.CreateEvaluationJobRequest): - request = data_labeling_service.CreateEvaluationJobRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if job is not None: - request.job = job - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_evaluation_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_evaluation_job(self, - request: Union[data_labeling_service.UpdateEvaluationJobRequest, dict] = None, - *, - evaluation_job: gcd_evaluation_job.EvaluationJob = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_evaluation_job.EvaluationJob: - r"""Updates an evaluation job. You can only update certain fields of - the job's - [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: - ``humanAnnotationConfig.instruction``, ``exampleCount``, and - ``exampleSamplePercentage``. - - If you want to change any other aspect of the evaluation job, - you must delete the job and create a new one. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.UpdateEvaluationJobRequest, dict]): - The request object. Request message for - UpdateEvaluationJob. - evaluation_job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): - Required. Evaluation job that is - going to be updated. - - This corresponds to the ``evaluation_job`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Mask for which fields to update. You can only - provide the following fields: - - - ``evaluationJobConfig.humanAnnotationConfig.instruction`` - - ``evaluationJobConfig.exampleCount`` - - ``evaluationJobConfig.exampleSamplePercentage`` - - You can provide more than one of these fields by - separating them with commas. - - 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.datalabeling_v1beta1.types.EvaluationJob: - Defines an evaluation job that runs periodically to generate - [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. - [Creating an evaluation - job](/ml-engine/docs/continuous-evaluation/create-job) - is the starting point for using continuous - evaluation. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([evaluation_job, 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 data_labeling_service.UpdateEvaluationJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.UpdateEvaluationJobRequest): - request = data_labeling_service.UpdateEvaluationJobRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if evaluation_job is not None: - request.evaluation_job = evaluation_job - 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_evaluation_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("evaluation_job.name", request.evaluation_job.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_evaluation_job(self, - request: Union[data_labeling_service.GetEvaluationJobRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> evaluation_job.EvaluationJob: - r"""Gets an evaluation job by resource name. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.GetEvaluationJobRequest, dict]): - The request object. Request message for - GetEvaluationJob. - name (str): - Required. Name of the evaluation job. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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.datalabeling_v1beta1.types.EvaluationJob: - Defines an evaluation job that runs periodically to generate - [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. - [Creating an evaluation - job](/ml-engine/docs/continuous-evaluation/create-job) - is the starting point for using continuous - evaluation. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.GetEvaluationJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.GetEvaluationJobRequest): - request = data_labeling_service.GetEvaluationJobRequest(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_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def pause_evaluation_job(self, - request: Union[data_labeling_service.PauseEvaluationJobRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Pauses an evaluation job. Pausing an evaluation job that is - already in a ``PAUSED`` state is a no-op. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.PauseEvaluationJobRequest, dict]): - The request object. Request message for - PauseEvaluationJob. - name (str): - Required. Name of the evaluation job that is going to be - paused. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.PauseEvaluationJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.PauseEvaluationJobRequest): - request = data_labeling_service.PauseEvaluationJobRequest(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.pause_evaluation_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def resume_evaluation_job(self, - request: Union[data_labeling_service.ResumeEvaluationJobRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Resumes a paused evaluation job. A deleted evaluation - job can't be resumed. Resuming a running or scheduled - evaluation job is a no-op. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ResumeEvaluationJobRequest, dict]): - The request object. Request message ResumeEvaluationJob. - name (str): - Required. Name of the evaluation job that is going to be - resumed. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.ResumeEvaluationJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ResumeEvaluationJobRequest): - request = data_labeling_service.ResumeEvaluationJobRequest(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.resume_evaluation_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def delete_evaluation_job(self, - request: Union[data_labeling_service.DeleteEvaluationJobRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Stops and deletes an evaluation job. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.DeleteEvaluationJobRequest, dict]): - The request object. Request message DeleteEvaluationJob. - name (str): - Required. Name of the evaluation job that is going to be - deleted. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}" - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity 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 data_labeling_service.DeleteEvaluationJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.DeleteEvaluationJobRequest): - request = data_labeling_service.DeleteEvaluationJobRequest(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_evaluation_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_evaluation_jobs(self, - request: Union[data_labeling_service.ListEvaluationJobsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEvaluationJobsPager: - r"""Lists all evaluation jobs within a project with - possible filters. Pagination is supported. - - Args: - request (Union[google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsRequest, dict]): - The request object. Request message for - ListEvaluationJobs. - parent (str): - Required. Evaluation job resource parent. Format: - "projects/{project_id}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. You can filter the jobs to list by model_id - (also known as model_name, as described in - [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) - or by evaluation job state (as described in - [EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]). - To filter by both criteria, use the ``AND`` operator or - the ``OR`` operator. For example, you can use the - following string for your filter: - "evaluation\ *job.model_id = {model_name} AND - evaluation*\ job.state = {evaluation_job_state}" - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datalabeling_v1beta1.services.data_labeling_service.pagers.ListEvaluationJobsPager: - Results for listing evaluation jobs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, filter]) - if request is 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 data_labeling_service.ListEvaluationJobsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, data_labeling_service.ListEvaluationJobsRequest): - request = data_labeling_service.ListEvaluationJobsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_evaluation_jobs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListEvaluationJobsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datalabeling", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataLabelingServiceClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py deleted file mode 100644 index b739a2c..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/pagers.py +++ /dev/null @@ -1,1121 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.datalabeling_v1beta1.types import annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import data_labeling_service -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job -from google.cloud.datalabeling_v1beta1.types import instruction - - -class ListDatasetsPager: - """A pager for iterating through ``list_datasets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``datasets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDatasets`` requests and continue to iterate - through the ``datasets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` - 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[..., data_labeling_service.ListDatasetsResponse], - request: data_labeling_service.ListDatasetsRequest, - response: data_labeling_service.ListDatasetsResponse, - *, - 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.datalabeling_v1beta1.types.ListDatasetsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse): - 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 = data_labeling_service.ListDatasetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.ListDatasetsResponse]: - 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[dataset.Dataset]: - for page in self.pages: - yield from page.datasets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDatasetsAsyncPager: - """A pager for iterating through ``list_datasets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``datasets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDatasets`` requests and continue to iterate - through the ``datasets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse` - 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[data_labeling_service.ListDatasetsResponse]], - request: data_labeling_service.ListDatasetsRequest, - response: data_labeling_service.ListDatasetsResponse, - *, - 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.datalabeling_v1beta1.types.ListDatasetsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListDatasetsResponse): - 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 = data_labeling_service.ListDatasetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.ListDatasetsResponse]: - 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[dataset.Dataset]: - async def async_generator(): - async for page in self.pages: - for response in page.datasets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDataItemsPager: - """A pager for iterating through ``list_data_items`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``data_items`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDataItems`` requests and continue to iterate - through the ``data_items`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` - 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[..., data_labeling_service.ListDataItemsResponse], - request: data_labeling_service.ListDataItemsRequest, - response: data_labeling_service.ListDataItemsResponse, - *, - 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.datalabeling_v1beta1.types.ListDataItemsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse): - 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 = data_labeling_service.ListDataItemsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.ListDataItemsResponse]: - 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[dataset.DataItem]: - for page in self.pages: - yield from page.data_items - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDataItemsAsyncPager: - """A pager for iterating through ``list_data_items`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``data_items`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDataItems`` requests and continue to iterate - through the ``data_items`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse` - 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[data_labeling_service.ListDataItemsResponse]], - request: data_labeling_service.ListDataItemsRequest, - response: data_labeling_service.ListDataItemsResponse, - *, - 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.datalabeling_v1beta1.types.ListDataItemsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListDataItemsResponse): - 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 = data_labeling_service.ListDataItemsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.ListDataItemsResponse]: - 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[dataset.DataItem]: - async def async_generator(): - async for page in self.pages: - for response in page.data_items: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAnnotatedDatasetsPager: - """A pager for iterating through ``list_annotated_datasets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``annotated_datasets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAnnotatedDatasets`` requests and continue to iterate - through the ``annotated_datasets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` - 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[..., data_labeling_service.ListAnnotatedDatasetsResponse], - request: data_labeling_service.ListAnnotatedDatasetsRequest, - response: data_labeling_service.ListAnnotatedDatasetsResponse, - *, - 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.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse): - 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 = data_labeling_service.ListAnnotatedDatasetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.ListAnnotatedDatasetsResponse]: - 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[dataset.AnnotatedDataset]: - for page in self.pages: - yield from page.annotated_datasets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAnnotatedDatasetsAsyncPager: - """A pager for iterating through ``list_annotated_datasets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``annotated_datasets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAnnotatedDatasets`` requests and continue to iterate - through the ``annotated_datasets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse` - 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[data_labeling_service.ListAnnotatedDatasetsResponse]], - request: data_labeling_service.ListAnnotatedDatasetsRequest, - response: data_labeling_service.ListAnnotatedDatasetsResponse, - *, - 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.datalabeling_v1beta1.types.ListAnnotatedDatasetsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListAnnotatedDatasetsResponse): - 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 = data_labeling_service.ListAnnotatedDatasetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.ListAnnotatedDatasetsResponse]: - 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[dataset.AnnotatedDataset]: - async def async_generator(): - async for page in self.pages: - for response in page.annotated_datasets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExamplesPager: - """A pager for iterating through ``list_examples`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``examples`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListExamples`` requests and continue to iterate - through the ``examples`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` - 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[..., data_labeling_service.ListExamplesResponse], - request: data_labeling_service.ListExamplesRequest, - response: data_labeling_service.ListExamplesResponse, - *, - 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.datalabeling_v1beta1.types.ListExamplesRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListExamplesResponse): - 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 = data_labeling_service.ListExamplesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.ListExamplesResponse]: - 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[dataset.Example]: - for page in self.pages: - yield from page.examples - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExamplesAsyncPager: - """A pager for iterating through ``list_examples`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``examples`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListExamples`` requests and continue to iterate - through the ``examples`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListExamplesResponse` - 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[data_labeling_service.ListExamplesResponse]], - request: data_labeling_service.ListExamplesRequest, - response: data_labeling_service.ListExamplesResponse, - *, - 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.datalabeling_v1beta1.types.ListExamplesRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListExamplesResponse): - 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 = data_labeling_service.ListExamplesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.ListExamplesResponse]: - 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[dataset.Example]: - async def async_generator(): - async for page in self.pages: - for response in page.examples: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAnnotationSpecSetsPager: - """A pager for iterating through ``list_annotation_spec_sets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``annotation_spec_sets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAnnotationSpecSets`` requests and continue to iterate - through the ``annotation_spec_sets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` - 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[..., data_labeling_service.ListAnnotationSpecSetsResponse], - request: data_labeling_service.ListAnnotationSpecSetsRequest, - response: data_labeling_service.ListAnnotationSpecSetsResponse, - *, - 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.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse): - 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 = data_labeling_service.ListAnnotationSpecSetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.ListAnnotationSpecSetsResponse]: - 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[annotation_spec_set.AnnotationSpecSet]: - for page in self.pages: - yield from page.annotation_spec_sets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAnnotationSpecSetsAsyncPager: - """A pager for iterating through ``list_annotation_spec_sets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``annotation_spec_sets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAnnotationSpecSets`` requests and continue to iterate - through the ``annotation_spec_sets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse` - 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[data_labeling_service.ListAnnotationSpecSetsResponse]], - request: data_labeling_service.ListAnnotationSpecSetsRequest, - response: data_labeling_service.ListAnnotationSpecSetsResponse, - *, - 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.datalabeling_v1beta1.types.ListAnnotationSpecSetsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListAnnotationSpecSetsResponse): - 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 = data_labeling_service.ListAnnotationSpecSetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.ListAnnotationSpecSetsResponse]: - 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[annotation_spec_set.AnnotationSpecSet]: - async def async_generator(): - async for page in self.pages: - for response in page.annotation_spec_sets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListInstructionsPager: - """A pager for iterating through ``list_instructions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``instructions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListInstructions`` requests and continue to iterate - through the ``instructions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` - 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[..., data_labeling_service.ListInstructionsResponse], - request: data_labeling_service.ListInstructionsRequest, - response: data_labeling_service.ListInstructionsResponse, - *, - 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.datalabeling_v1beta1.types.ListInstructionsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse): - 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 = data_labeling_service.ListInstructionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.ListInstructionsResponse]: - 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[instruction.Instruction]: - for page in self.pages: - yield from page.instructions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListInstructionsAsyncPager: - """A pager for iterating through ``list_instructions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``instructions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListInstructions`` requests and continue to iterate - through the ``instructions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse` - 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[data_labeling_service.ListInstructionsResponse]], - request: data_labeling_service.ListInstructionsRequest, - response: data_labeling_service.ListInstructionsResponse, - *, - 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.datalabeling_v1beta1.types.ListInstructionsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListInstructionsResponse): - 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 = data_labeling_service.ListInstructionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.ListInstructionsResponse]: - 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[instruction.Instruction]: - async def async_generator(): - async for page in self.pages: - for response in page.instructions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchEvaluationsPager: - """A pager for iterating through ``search_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``evaluations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchEvaluations`` requests and continue to iterate - through the ``evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` - 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[..., data_labeling_service.SearchEvaluationsResponse], - request: data_labeling_service.SearchEvaluationsRequest, - response: data_labeling_service.SearchEvaluationsResponse, - *, - 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.datalabeling_v1beta1.types.SearchEvaluationsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse): - 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 = data_labeling_service.SearchEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.SearchEvaluationsResponse]: - 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 SearchEvaluationsAsyncPager: - """A pager for iterating through ``search_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``evaluations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchEvaluations`` requests and continue to iterate - through the ``evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse` - 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[data_labeling_service.SearchEvaluationsResponse]], - request: data_labeling_service.SearchEvaluationsRequest, - response: data_labeling_service.SearchEvaluationsResponse, - *, - 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.datalabeling_v1beta1.types.SearchEvaluationsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.SearchEvaluationsResponse): - 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 = data_labeling_service.SearchEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.SearchEvaluationsResponse]: - 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) - - -class SearchExampleComparisonsPager: - """A pager for iterating through ``search_example_comparisons`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``example_comparisons`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchExampleComparisons`` requests and continue to iterate - through the ``example_comparisons`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` - 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[..., data_labeling_service.SearchExampleComparisonsResponse], - request: data_labeling_service.SearchExampleComparisonsRequest, - response: data_labeling_service.SearchExampleComparisonsResponse, - *, - 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.datalabeling_v1beta1.types.SearchExampleComparisonsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse): - 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 = data_labeling_service.SearchExampleComparisonsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.SearchExampleComparisonsResponse]: - 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[data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison]: - for page in self.pages: - yield from page.example_comparisons - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchExampleComparisonsAsyncPager: - """A pager for iterating through ``search_example_comparisons`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``example_comparisons`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchExampleComparisons`` requests and continue to iterate - through the ``example_comparisons`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse` - 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[data_labeling_service.SearchExampleComparisonsResponse]], - request: data_labeling_service.SearchExampleComparisonsRequest, - response: data_labeling_service.SearchExampleComparisonsResponse, - *, - 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.datalabeling_v1beta1.types.SearchExampleComparisonsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse): - 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 = data_labeling_service.SearchExampleComparisonsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.SearchExampleComparisonsResponse]: - 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[data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison]: - async def async_generator(): - async for page in self.pages: - for response in page.example_comparisons: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEvaluationJobsPager: - """A pager for iterating through ``list_evaluation_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``evaluation_jobs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEvaluationJobs`` requests and continue to iterate - through the ``evaluation_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` - 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[..., data_labeling_service.ListEvaluationJobsResponse], - request: data_labeling_service.ListEvaluationJobsRequest, - response: data_labeling_service.ListEvaluationJobsResponse, - *, - 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.datalabeling_v1beta1.types.ListEvaluationJobsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse): - 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 = data_labeling_service.ListEvaluationJobsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[data_labeling_service.ListEvaluationJobsResponse]: - 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_job.EvaluationJob]: - for page in self.pages: - yield from page.evaluation_jobs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEvaluationJobsAsyncPager: - """A pager for iterating through ``list_evaluation_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``evaluation_jobs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEvaluationJobs`` requests and continue to iterate - through the ``evaluation_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse` - 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[data_labeling_service.ListEvaluationJobsResponse]], - request: data_labeling_service.ListEvaluationJobsRequest, - response: data_labeling_service.ListEvaluationJobsResponse, - *, - 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.datalabeling_v1beta1.types.ListEvaluationJobsRequest): - The initial request object. - response (google.cloud.datalabeling_v1beta1.types.ListEvaluationJobsResponse): - 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 = data_labeling_service.ListEvaluationJobsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[data_labeling_service.ListEvaluationJobsResponse]: - 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_job.EvaluationJob]: - async def async_generator(): - async for page in self.pages: - for response in page.evaluation_jobs: - 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/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py deleted file mode 100644 index 52111f1..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DataLabelingServiceTransport -from .grpc import DataLabelingServiceGrpcTransport -from .grpc_asyncio import DataLabelingServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DataLabelingServiceTransport]] -_transport_registry['grpc'] = DataLabelingServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DataLabelingServiceGrpcAsyncIOTransport - -__all__ = ( - 'DataLabelingServiceTransport', - 'DataLabelingServiceGrpcTransport', - 'DataLabelingServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py deleted file mode 100644 index 88bf88a..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py +++ /dev/null @@ -1,802 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import data_labeling_service -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job -from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job -from google.cloud.datalabeling_v1beta1.types import instruction -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-datalabeling', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class DataLabelingServiceTransport(abc.ABC): - """Abstract transport class for DataLabelingService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'datalabeling.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_dataset: gapic_v1.method.wrap_method( - self.create_dataset, - default_timeout=30.0, - client_info=client_info, - ), - self.get_dataset: gapic_v1.method.wrap_method( - self.get_dataset, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_datasets: gapic_v1.method.wrap_method( - self.list_datasets, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_dataset: gapic_v1.method.wrap_method( - self.delete_dataset, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_data: gapic_v1.method.wrap_method( - self.import_data, - default_timeout=30.0, - client_info=client_info, - ), - self.export_data: gapic_v1.method.wrap_method( - self.export_data, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_data_item: gapic_v1.method.wrap_method( - self.get_data_item, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_data_items: gapic_v1.method.wrap_method( - self.list_data_items, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_annotated_dataset: gapic_v1.method.wrap_method( - self.get_annotated_dataset, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_annotated_datasets: gapic_v1.method.wrap_method( - self.list_annotated_datasets, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_annotated_dataset: gapic_v1.method.wrap_method( - self.delete_annotated_dataset, - default_timeout=None, - client_info=client_info, - ), - self.label_image: gapic_v1.method.wrap_method( - self.label_image, - default_timeout=30.0, - client_info=client_info, - ), - self.label_video: gapic_v1.method.wrap_method( - self.label_video, - default_timeout=30.0, - client_info=client_info, - ), - self.label_text: gapic_v1.method.wrap_method( - self.label_text, - default_timeout=30.0, - client_info=client_info, - ), - self.get_example: gapic_v1.method.wrap_method( - self.get_example, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_examples: gapic_v1.method.wrap_method( - self.list_examples, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_annotation_spec_set: gapic_v1.method.wrap_method( - self.create_annotation_spec_set, - default_timeout=30.0, - client_info=client_info, - ), - self.get_annotation_spec_set: gapic_v1.method.wrap_method( - self.get_annotation_spec_set, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_annotation_spec_sets: gapic_v1.method.wrap_method( - self.list_annotation_spec_sets, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_annotation_spec_set: gapic_v1.method.wrap_method( - self.delete_annotation_spec_set, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_instruction: gapic_v1.method.wrap_method( - self.create_instruction, - default_timeout=30.0, - client_info=client_info, - ), - self.get_instruction: gapic_v1.method.wrap_method( - self.get_instruction, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_instructions: gapic_v1.method.wrap_method( - self.list_instructions, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_instruction: gapic_v1.method.wrap_method( - self.delete_instruction, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_evaluation: gapic_v1.method.wrap_method( - self.get_evaluation, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.search_evaluations: gapic_v1.method.wrap_method( - self.search_evaluations, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.search_example_comparisons: gapic_v1.method.wrap_method( - self.search_example_comparisons, - default_timeout=30.0, - client_info=client_info, - ), - self.create_evaluation_job: gapic_v1.method.wrap_method( - self.create_evaluation_job, - default_timeout=30.0, - client_info=client_info, - ), - self.update_evaluation_job: gapic_v1.method.wrap_method( - self.update_evaluation_job, - default_timeout=30.0, - client_info=client_info, - ), - self.get_evaluation_job: gapic_v1.method.wrap_method( - self.get_evaluation_job, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.pause_evaluation_job: gapic_v1.method.wrap_method( - self.pause_evaluation_job, - default_timeout=30.0, - client_info=client_info, - ), - self.resume_evaluation_job: gapic_v1.method.wrap_method( - self.resume_evaluation_job, - default_timeout=30.0, - client_info=client_info, - ), - self.delete_evaluation_job: gapic_v1.method.wrap_method( - self.delete_evaluation_job, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_evaluation_jobs: gapic_v1.method.wrap_method( - self.list_evaluation_jobs, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.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) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_dataset(self) -> Callable[ - [data_labeling_service.CreateDatasetRequest], - Union[ - gcd_dataset.Dataset, - Awaitable[gcd_dataset.Dataset] - ]]: - raise NotImplementedError() - - @property - def get_dataset(self) -> Callable[ - [data_labeling_service.GetDatasetRequest], - Union[ - dataset.Dataset, - Awaitable[dataset.Dataset] - ]]: - raise NotImplementedError() - - @property - def list_datasets(self) -> Callable[ - [data_labeling_service.ListDatasetsRequest], - Union[ - data_labeling_service.ListDatasetsResponse, - Awaitable[data_labeling_service.ListDatasetsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_dataset(self) -> Callable[ - [data_labeling_service.DeleteDatasetRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_data(self) -> Callable[ - [data_labeling_service.ImportDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_data(self) -> Callable[ - [data_labeling_service.ExportDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_data_item(self) -> Callable[ - [data_labeling_service.GetDataItemRequest], - Union[ - dataset.DataItem, - Awaitable[dataset.DataItem] - ]]: - raise NotImplementedError() - - @property - def list_data_items(self) -> Callable[ - [data_labeling_service.ListDataItemsRequest], - Union[ - data_labeling_service.ListDataItemsResponse, - Awaitable[data_labeling_service.ListDataItemsResponse] - ]]: - raise NotImplementedError() - - @property - def get_annotated_dataset(self) -> Callable[ - [data_labeling_service.GetAnnotatedDatasetRequest], - Union[ - dataset.AnnotatedDataset, - Awaitable[dataset.AnnotatedDataset] - ]]: - raise NotImplementedError() - - @property - def list_annotated_datasets(self) -> Callable[ - [data_labeling_service.ListAnnotatedDatasetsRequest], - Union[ - data_labeling_service.ListAnnotatedDatasetsResponse, - Awaitable[data_labeling_service.ListAnnotatedDatasetsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_annotated_dataset(self) -> Callable[ - [data_labeling_service.DeleteAnnotatedDatasetRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def label_image(self) -> Callable[ - [data_labeling_service.LabelImageRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def label_video(self) -> Callable[ - [data_labeling_service.LabelVideoRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def label_text(self) -> Callable[ - [data_labeling_service.LabelTextRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_example(self) -> Callable[ - [data_labeling_service.GetExampleRequest], - Union[ - dataset.Example, - Awaitable[dataset.Example] - ]]: - raise NotImplementedError() - - @property - def list_examples(self) -> Callable[ - [data_labeling_service.ListExamplesRequest], - Union[ - data_labeling_service.ListExamplesResponse, - Awaitable[data_labeling_service.ListExamplesResponse] - ]]: - raise NotImplementedError() - - @property - def create_annotation_spec_set(self) -> Callable[ - [data_labeling_service.CreateAnnotationSpecSetRequest], - Union[ - gcd_annotation_spec_set.AnnotationSpecSet, - Awaitable[gcd_annotation_spec_set.AnnotationSpecSet] - ]]: - raise NotImplementedError() - - @property - def get_annotation_spec_set(self) -> Callable[ - [data_labeling_service.GetAnnotationSpecSetRequest], - Union[ - annotation_spec_set.AnnotationSpecSet, - Awaitable[annotation_spec_set.AnnotationSpecSet] - ]]: - raise NotImplementedError() - - @property - def list_annotation_spec_sets(self) -> Callable[ - [data_labeling_service.ListAnnotationSpecSetsRequest], - Union[ - data_labeling_service.ListAnnotationSpecSetsResponse, - Awaitable[data_labeling_service.ListAnnotationSpecSetsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_annotation_spec_set(self) -> Callable[ - [data_labeling_service.DeleteAnnotationSpecSetRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_instruction(self) -> Callable[ - [data_labeling_service.CreateInstructionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_instruction(self) -> Callable[ - [data_labeling_service.GetInstructionRequest], - Union[ - instruction.Instruction, - Awaitable[instruction.Instruction] - ]]: - raise NotImplementedError() - - @property - def list_instructions(self) -> Callable[ - [data_labeling_service.ListInstructionsRequest], - Union[ - data_labeling_service.ListInstructionsResponse, - Awaitable[data_labeling_service.ListInstructionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_instruction(self) -> Callable[ - [data_labeling_service.DeleteInstructionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_evaluation(self) -> Callable[ - [data_labeling_service.GetEvaluationRequest], - Union[ - evaluation.Evaluation, - Awaitable[evaluation.Evaluation] - ]]: - raise NotImplementedError() - - @property - def search_evaluations(self) -> Callable[ - [data_labeling_service.SearchEvaluationsRequest], - Union[ - data_labeling_service.SearchEvaluationsResponse, - Awaitable[data_labeling_service.SearchEvaluationsResponse] - ]]: - raise NotImplementedError() - - @property - def search_example_comparisons(self) -> Callable[ - [data_labeling_service.SearchExampleComparisonsRequest], - Union[ - data_labeling_service.SearchExampleComparisonsResponse, - Awaitable[data_labeling_service.SearchExampleComparisonsResponse] - ]]: - raise NotImplementedError() - - @property - def create_evaluation_job(self) -> Callable[ - [data_labeling_service.CreateEvaluationJobRequest], - Union[ - evaluation_job.EvaluationJob, - Awaitable[evaluation_job.EvaluationJob] - ]]: - raise NotImplementedError() - - @property - def update_evaluation_job(self) -> Callable[ - [data_labeling_service.UpdateEvaluationJobRequest], - Union[ - gcd_evaluation_job.EvaluationJob, - Awaitable[gcd_evaluation_job.EvaluationJob] - ]]: - raise NotImplementedError() - - @property - def get_evaluation_job(self) -> Callable[ - [data_labeling_service.GetEvaluationJobRequest], - Union[ - evaluation_job.EvaluationJob, - Awaitable[evaluation_job.EvaluationJob] - ]]: - raise NotImplementedError() - - @property - def pause_evaluation_job(self) -> Callable[ - [data_labeling_service.PauseEvaluationJobRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def resume_evaluation_job(self) -> Callable[ - [data_labeling_service.ResumeEvaluationJobRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_evaluation_job(self) -> Callable[ - [data_labeling_service.DeleteEvaluationJobRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_evaluation_jobs(self) -> Callable[ - [data_labeling_service.ListEvaluationJobsRequest], - Union[ - data_labeling_service.ListEvaluationJobsResponse, - Awaitable[data_labeling_service.ListEvaluationJobsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'DataLabelingServiceTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py deleted file mode 100644 index 117308e..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc.py +++ /dev/null @@ -1,1177 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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.datalabeling_v1beta1.types import annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import data_labeling_service -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job -from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job -from google.cloud.datalabeling_v1beta1.types import instruction -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO - - -class DataLabelingServiceGrpcTransport(DataLabelingServiceTransport): - """gRPC backend transport for DataLabelingService. - - Service for the AI Platform Data Labeling API. - - 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 = 'datalabeling.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'datalabeling.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity 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 create_dataset(self) -> Callable[ - [data_labeling_service.CreateDatasetRequest], - gcd_dataset.Dataset]: - r"""Return a callable for the create dataset method over gRPC. - - Creates dataset. If success return a Dataset - resource. - - Returns: - Callable[[~.CreateDatasetRequest], - ~.Dataset]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['create_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateDataset', - request_serializer=data_labeling_service.CreateDatasetRequest.serialize, - response_deserializer=gcd_dataset.Dataset.deserialize, - ) - return self._stubs['create_dataset'] - - @property - def get_dataset(self) -> Callable[ - [data_labeling_service.GetDatasetRequest], - dataset.Dataset]: - r"""Return a callable for the get dataset method over gRPC. - - Gets dataset by resource name. - - Returns: - Callable[[~.GetDatasetRequest], - ~.Dataset]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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' not in self._stubs: - self._stubs['get_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataset', - request_serializer=data_labeling_service.GetDatasetRequest.serialize, - response_deserializer=dataset.Dataset.deserialize, - ) - return self._stubs['get_dataset'] - - @property - def list_datasets(self) -> Callable[ - [data_labeling_service.ListDatasetsRequest], - data_labeling_service.ListDatasetsResponse]: - r"""Return a callable for the list datasets method over gRPC. - - Lists datasets under a project. Pagination is - supported. - - Returns: - Callable[[~.ListDatasetsRequest], - ~.ListDatasetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_datasets' not in self._stubs: - self._stubs['list_datasets'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDatasets', - request_serializer=data_labeling_service.ListDatasetsRequest.serialize, - response_deserializer=data_labeling_service.ListDatasetsResponse.deserialize, - ) - return self._stubs['list_datasets'] - - @property - def delete_dataset(self) -> Callable[ - [data_labeling_service.DeleteDatasetRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete dataset method over gRPC. - - Deletes a dataset by resource name. - - Returns: - Callable[[~.DeleteDatasetRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['delete_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteDataset', - request_serializer=data_labeling_service.DeleteDatasetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_dataset'] - - @property - def import_data(self) -> Callable[ - [data_labeling_service.ImportDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import data method over gRPC. - - Imports data into dataset based on source locations - defined in request. It can be called multiple times for - the same dataset. Each dataset can only have one long - running operation running on it. For example, no - labeling task (also long running operation) can be - started while importing is still ongoing. Vice versa. - - Returns: - Callable[[~.ImportDataRequest], - ~.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_data' not in self._stubs: - self._stubs['import_data'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ImportData', - request_serializer=data_labeling_service.ImportDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_data'] - - @property - def export_data(self) -> Callable[ - [data_labeling_service.ExportDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the export data method over gRPC. - - Exports data and annotations from dataset. - - Returns: - Callable[[~.ExportDataRequest], - ~.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 'export_data' not in self._stubs: - self._stubs['export_data'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ExportData', - request_serializer=data_labeling_service.ExportDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_data'] - - @property - def get_data_item(self) -> Callable[ - [data_labeling_service.GetDataItemRequest], - dataset.DataItem]: - r"""Return a callable for the get data item method over gRPC. - - Gets a data item in a dataset by resource name. This - API can be called after data are imported into dataset. - - Returns: - Callable[[~.GetDataItemRequest], - ~.DataItem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_item' not in self._stubs: - self._stubs['get_data_item'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataItem', - request_serializer=data_labeling_service.GetDataItemRequest.serialize, - response_deserializer=dataset.DataItem.deserialize, - ) - return self._stubs['get_data_item'] - - @property - def list_data_items(self) -> Callable[ - [data_labeling_service.ListDataItemsRequest], - data_labeling_service.ListDataItemsResponse]: - r"""Return a callable for the list data items method over gRPC. - - Lists data items in a dataset. This API can be called - after data are imported into dataset. Pagination is - supported. - - Returns: - Callable[[~.ListDataItemsRequest], - ~.ListDataItemsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_items' not in self._stubs: - self._stubs['list_data_items'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDataItems', - request_serializer=data_labeling_service.ListDataItemsRequest.serialize, - response_deserializer=data_labeling_service.ListDataItemsResponse.deserialize, - ) - return self._stubs['list_data_items'] - - @property - def get_annotated_dataset(self) -> Callable[ - [data_labeling_service.GetAnnotatedDatasetRequest], - dataset.AnnotatedDataset]: - r"""Return a callable for the get annotated dataset method over gRPC. - - Gets an annotated dataset by resource name. - - Returns: - Callable[[~.GetAnnotatedDatasetRequest], - ~.AnnotatedDataset]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: - self._stubs['get_annotated_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotatedDataset', - request_serializer=data_labeling_service.GetAnnotatedDatasetRequest.serialize, - response_deserializer=dataset.AnnotatedDataset.deserialize, - ) - return self._stubs['get_annotated_dataset'] - - @property - def list_annotated_datasets(self) -> Callable[ - [data_labeling_service.ListAnnotatedDatasetsRequest], - data_labeling_service.ListAnnotatedDatasetsResponse]: - r"""Return a callable for the list annotated datasets method over gRPC. - - Lists annotated datasets for a dataset. Pagination is - supported. - - Returns: - Callable[[~.ListAnnotatedDatasetsRequest], - ~.ListAnnotatedDatasetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotated_datasets' not in self._stubs: - self._stubs['list_annotated_datasets'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotatedDatasets', - request_serializer=data_labeling_service.ListAnnotatedDatasetsRequest.serialize, - response_deserializer=data_labeling_service.ListAnnotatedDatasetsResponse.deserialize, - ) - return self._stubs['list_annotated_datasets'] - - @property - def delete_annotated_dataset(self) -> Callable[ - [data_labeling_service.DeleteAnnotatedDatasetRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete annotated dataset method over gRPC. - - Deletes an annotated dataset by resource name. - - Returns: - Callable[[~.DeleteAnnotatedDatasetRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: - self._stubs['delete_annotated_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotatedDataset', - request_serializer=data_labeling_service.DeleteAnnotatedDatasetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_annotated_dataset'] - - @property - def label_image(self) -> Callable[ - [data_labeling_service.LabelImageRequest], - operations_pb2.Operation]: - r"""Return a callable for the label image method over gRPC. - - Starts a labeling task for image. The type of image - labeling task is configured by feature in the request. - - Returns: - Callable[[~.LabelImageRequest], - ~.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 'label_image' not in self._stubs: - self._stubs['label_image'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelImage', - request_serializer=data_labeling_service.LabelImageRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['label_image'] - - @property - def label_video(self) -> Callable[ - [data_labeling_service.LabelVideoRequest], - operations_pb2.Operation]: - r"""Return a callable for the label video method over gRPC. - - Starts a labeling task for video. The type of video - labeling task is configured by feature in the request. - - Returns: - Callable[[~.LabelVideoRequest], - ~.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 'label_video' not in self._stubs: - self._stubs['label_video'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelVideo', - request_serializer=data_labeling_service.LabelVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['label_video'] - - @property - def label_text(self) -> Callable[ - [data_labeling_service.LabelTextRequest], - operations_pb2.Operation]: - r"""Return a callable for the label text method over gRPC. - - Starts a labeling task for text. The type of text - labeling task is configured by feature in the request. - - Returns: - Callable[[~.LabelTextRequest], - ~.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 'label_text' not in self._stubs: - self._stubs['label_text'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelText', - request_serializer=data_labeling_service.LabelTextRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['label_text'] - - @property - def get_example(self) -> Callable[ - [data_labeling_service.GetExampleRequest], - dataset.Example]: - r"""Return a callable for the get example method over gRPC. - - Gets an example by resource name, including both data - and annotation. - - Returns: - Callable[[~.GetExampleRequest], - ~.Example]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_example' not in self._stubs: - self._stubs['get_example'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetExample', - request_serializer=data_labeling_service.GetExampleRequest.serialize, - response_deserializer=dataset.Example.deserialize, - ) - return self._stubs['get_example'] - - @property - def list_examples(self) -> Callable[ - [data_labeling_service.ListExamplesRequest], - data_labeling_service.ListExamplesResponse]: - r"""Return a callable for the list examples method over gRPC. - - Lists examples in an annotated dataset. Pagination is - supported. - - Returns: - Callable[[~.ListExamplesRequest], - ~.ListExamplesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_examples' not in self._stubs: - self._stubs['list_examples'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListExamples', - request_serializer=data_labeling_service.ListExamplesRequest.serialize, - response_deserializer=data_labeling_service.ListExamplesResponse.deserialize, - ) - return self._stubs['list_examples'] - - @property - def create_annotation_spec_set(self) -> Callable[ - [data_labeling_service.CreateAnnotationSpecSetRequest], - gcd_annotation_spec_set.AnnotationSpecSet]: - r"""Return a callable for the create annotation spec set method over gRPC. - - Creates an annotation spec set by providing a set of - labels. - - Returns: - Callable[[~.CreateAnnotationSpecSetRequest], - ~.AnnotationSpecSet]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: - self._stubs['create_annotation_spec_set'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateAnnotationSpecSet', - request_serializer=data_labeling_service.CreateAnnotationSpecSetRequest.serialize, - response_deserializer=gcd_annotation_spec_set.AnnotationSpecSet.deserialize, - ) - return self._stubs['create_annotation_spec_set'] - - @property - def get_annotation_spec_set(self) -> Callable[ - [data_labeling_service.GetAnnotationSpecSetRequest], - annotation_spec_set.AnnotationSpecSet]: - r"""Return a callable for the get annotation spec set method over gRPC. - - Gets an annotation spec set by resource name. - - Returns: - Callable[[~.GetAnnotationSpecSetRequest], - ~.AnnotationSpecSet]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: - self._stubs['get_annotation_spec_set'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotationSpecSet', - request_serializer=data_labeling_service.GetAnnotationSpecSetRequest.serialize, - response_deserializer=annotation_spec_set.AnnotationSpecSet.deserialize, - ) - return self._stubs['get_annotation_spec_set'] - - @property - def list_annotation_spec_sets(self) -> Callable[ - [data_labeling_service.ListAnnotationSpecSetsRequest], - data_labeling_service.ListAnnotationSpecSetsResponse]: - r"""Return a callable for the list annotation spec sets method over gRPC. - - Lists annotation spec sets for a project. Pagination - is supported. - - Returns: - Callable[[~.ListAnnotationSpecSetsRequest], - ~.ListAnnotationSpecSetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_sets' not in self._stubs: - self._stubs['list_annotation_spec_sets'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotationSpecSets', - request_serializer=data_labeling_service.ListAnnotationSpecSetsRequest.serialize, - response_deserializer=data_labeling_service.ListAnnotationSpecSetsResponse.deserialize, - ) - return self._stubs['list_annotation_spec_sets'] - - @property - def delete_annotation_spec_set(self) -> Callable[ - [data_labeling_service.DeleteAnnotationSpecSetRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete annotation spec set method over gRPC. - - Deletes an annotation spec set by resource name. - - Returns: - Callable[[~.DeleteAnnotationSpecSetRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: - self._stubs['delete_annotation_spec_set'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotationSpecSet', - request_serializer=data_labeling_service.DeleteAnnotationSpecSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_annotation_spec_set'] - - @property - def create_instruction(self) -> Callable[ - [data_labeling_service.CreateInstructionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create instruction method over gRPC. - - Creates an instruction for how data should be - labeled. - - Returns: - Callable[[~.CreateInstructionRequest], - ~.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 'create_instruction' not in self._stubs: - self._stubs['create_instruction'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateInstruction', - request_serializer=data_labeling_service.CreateInstructionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_instruction'] - - @property - def get_instruction(self) -> Callable[ - [data_labeling_service.GetInstructionRequest], - instruction.Instruction]: - r"""Return a callable for the get instruction method over gRPC. - - Gets an instruction by resource name. - - Returns: - Callable[[~.GetInstructionRequest], - ~.Instruction]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instruction' not in self._stubs: - self._stubs['get_instruction'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetInstruction', - request_serializer=data_labeling_service.GetInstructionRequest.serialize, - response_deserializer=instruction.Instruction.deserialize, - ) - return self._stubs['get_instruction'] - - @property - def list_instructions(self) -> Callable[ - [data_labeling_service.ListInstructionsRequest], - data_labeling_service.ListInstructionsResponse]: - r"""Return a callable for the list instructions method over gRPC. - - Lists instructions for a project. Pagination is - supported. - - Returns: - Callable[[~.ListInstructionsRequest], - ~.ListInstructionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instructions' not in self._stubs: - self._stubs['list_instructions'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListInstructions', - request_serializer=data_labeling_service.ListInstructionsRequest.serialize, - response_deserializer=data_labeling_service.ListInstructionsResponse.deserialize, - ) - return self._stubs['list_instructions'] - - @property - def delete_instruction(self) -> Callable[ - [data_labeling_service.DeleteInstructionRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete instruction method over gRPC. - - Deletes an instruction object by resource name. - - Returns: - Callable[[~.DeleteInstructionRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instruction' not in self._stubs: - self._stubs['delete_instruction'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteInstruction', - request_serializer=data_labeling_service.DeleteInstructionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_instruction'] - - @property - def get_evaluation(self) -> Callable[ - [data_labeling_service.GetEvaluationRequest], - evaluation.Evaluation]: - r"""Return a callable for the get evaluation method over gRPC. - - Gets an evaluation by resource name (to search, use - [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). - - 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.datalabeling.v1beta1.DataLabelingService/GetEvaluation', - request_serializer=data_labeling_service.GetEvaluationRequest.serialize, - response_deserializer=evaluation.Evaluation.deserialize, - ) - return self._stubs['get_evaluation'] - - @property - def search_evaluations(self) -> Callable[ - [data_labeling_service.SearchEvaluationsRequest], - data_labeling_service.SearchEvaluationsResponse]: - r"""Return a callable for the search evaluations method over gRPC. - - Searches - [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] - within a project. - - Returns: - Callable[[~.SearchEvaluationsRequest], - ~.SearchEvaluationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_evaluations' not in self._stubs: - self._stubs['search_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchEvaluations', - request_serializer=data_labeling_service.SearchEvaluationsRequest.serialize, - response_deserializer=data_labeling_service.SearchEvaluationsResponse.deserialize, - ) - return self._stubs['search_evaluations'] - - @property - def search_example_comparisons(self) -> Callable[ - [data_labeling_service.SearchExampleComparisonsRequest], - data_labeling_service.SearchExampleComparisonsResponse]: - r"""Return a callable for the search example comparisons method over gRPC. - - Searches example comparisons from an evaluation. The - return format is a list of example comparisons that show - ground truth and prediction(s) for a single input. - Search by providing an evaluation ID. - - Returns: - Callable[[~.SearchExampleComparisonsRequest], - ~.SearchExampleComparisonsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_example_comparisons' not in self._stubs: - self._stubs['search_example_comparisons'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchExampleComparisons', - request_serializer=data_labeling_service.SearchExampleComparisonsRequest.serialize, - response_deserializer=data_labeling_service.SearchExampleComparisonsResponse.deserialize, - ) - return self._stubs['search_example_comparisons'] - - @property - def create_evaluation_job(self) -> Callable[ - [data_labeling_service.CreateEvaluationJobRequest], - evaluation_job.EvaluationJob]: - r"""Return a callable for the create evaluation job method over gRPC. - - Creates an evaluation job. - - Returns: - Callable[[~.CreateEvaluationJobRequest], - ~.EvaluationJob]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: - self._stubs['create_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateEvaluationJob', - request_serializer=data_labeling_service.CreateEvaluationJobRequest.serialize, - response_deserializer=evaluation_job.EvaluationJob.deserialize, - ) - return self._stubs['create_evaluation_job'] - - @property - def update_evaluation_job(self) -> Callable[ - [data_labeling_service.UpdateEvaluationJobRequest], - gcd_evaluation_job.EvaluationJob]: - r"""Return a callable for the update evaluation job method over gRPC. - - Updates an evaluation job. You can only update certain fields of - the job's - [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: - ``humanAnnotationConfig.instruction``, ``exampleCount``, and - ``exampleSamplePercentage``. - - If you want to change any other aspect of the evaluation job, - you must delete the job and create a new one. - - Returns: - Callable[[~.UpdateEvaluationJobRequest], - ~.EvaluationJob]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: - self._stubs['update_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/UpdateEvaluationJob', - request_serializer=data_labeling_service.UpdateEvaluationJobRequest.serialize, - response_deserializer=gcd_evaluation_job.EvaluationJob.deserialize, - ) - return self._stubs['update_evaluation_job'] - - @property - def get_evaluation_job(self) -> Callable[ - [data_labeling_service.GetEvaluationJobRequest], - evaluation_job.EvaluationJob]: - r"""Return a callable for the get evaluation job method over gRPC. - - Gets an evaluation job by resource name. - - Returns: - Callable[[~.GetEvaluationJobRequest], - ~.EvaluationJob]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_job' not in self._stubs: - self._stubs['get_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetEvaluationJob', - request_serializer=data_labeling_service.GetEvaluationJobRequest.serialize, - response_deserializer=evaluation_job.EvaluationJob.deserialize, - ) - return self._stubs['get_evaluation_job'] - - @property - def pause_evaluation_job(self) -> Callable[ - [data_labeling_service.PauseEvaluationJobRequest], - empty_pb2.Empty]: - r"""Return a callable for the pause evaluation job method over gRPC. - - Pauses an evaluation job. Pausing an evaluation job that is - already in a ``PAUSED`` state is a no-op. - - Returns: - Callable[[~.PauseEvaluationJobRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'pause_evaluation_job' not in self._stubs: - self._stubs['pause_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/PauseEvaluationJob', - request_serializer=data_labeling_service.PauseEvaluationJobRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['pause_evaluation_job'] - - @property - def resume_evaluation_job(self) -> Callable[ - [data_labeling_service.ResumeEvaluationJobRequest], - empty_pb2.Empty]: - r"""Return a callable for the resume evaluation job method over gRPC. - - Resumes a paused evaluation job. A deleted evaluation - job can't be resumed. Resuming a running or scheduled - evaluation job is a no-op. - - Returns: - Callable[[~.ResumeEvaluationJobRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'resume_evaluation_job' not in self._stubs: - self._stubs['resume_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ResumeEvaluationJob', - request_serializer=data_labeling_service.ResumeEvaluationJobRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['resume_evaluation_job'] - - @property - def delete_evaluation_job(self) -> Callable[ - [data_labeling_service.DeleteEvaluationJobRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete evaluation job method over gRPC. - - Stops and deletes an evaluation job. - - Returns: - Callable[[~.DeleteEvaluationJobRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: - self._stubs['delete_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteEvaluationJob', - request_serializer=data_labeling_service.DeleteEvaluationJobRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_evaluation_job'] - - @property - def list_evaluation_jobs(self) -> Callable[ - [data_labeling_service.ListEvaluationJobsRequest], - data_labeling_service.ListEvaluationJobsResponse]: - r"""Return a callable for the list evaluation jobs method over gRPC. - - Lists all evaluation jobs within a project with - possible filters. Pagination is supported. - - Returns: - Callable[[~.ListEvaluationJobsRequest], - ~.ListEvaluationJobsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_jobs' not in self._stubs: - self._stubs['list_evaluation_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListEvaluationJobs', - request_serializer=data_labeling_service.ListEvaluationJobsRequest.serialize, - response_deserializer=data_labeling_service.ListEvaluationJobsResponse.deserialize, - ) - return self._stubs['list_evaluation_jobs'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'DataLabelingServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py deleted file mode 100644 index 9dc51c3..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,1182 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import data_labeling_service -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job -from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job -from google.cloud.datalabeling_v1beta1.types import instruction -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DataLabelingServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DataLabelingServiceGrpcTransport - - -class DataLabelingServiceGrpcAsyncIOTransport(DataLabelingServiceTransport): - """gRPC AsyncIO backend transport for DataLabelingService. - - Service for the AI Platform Data Labeling API. - - 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 = 'datalabeling.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'datalabeling.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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. - """ - # Sanity 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 create_dataset(self) -> Callable[ - [data_labeling_service.CreateDatasetRequest], - Awaitable[gcd_dataset.Dataset]]: - r"""Return a callable for the create dataset method over gRPC. - - Creates dataset. If success return a Dataset - resource. - - Returns: - Callable[[~.CreateDatasetRequest], - Awaitable[~.Dataset]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['create_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateDataset', - request_serializer=data_labeling_service.CreateDatasetRequest.serialize, - response_deserializer=gcd_dataset.Dataset.deserialize, - ) - return self._stubs['create_dataset'] - - @property - def get_dataset(self) -> Callable[ - [data_labeling_service.GetDatasetRequest], - Awaitable[dataset.Dataset]]: - r"""Return a callable for the get dataset method over gRPC. - - Gets dataset by resource name. - - Returns: - Callable[[~.GetDatasetRequest], - Awaitable[~.Dataset]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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' not in self._stubs: - self._stubs['get_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataset', - request_serializer=data_labeling_service.GetDatasetRequest.serialize, - response_deserializer=dataset.Dataset.deserialize, - ) - return self._stubs['get_dataset'] - - @property - def list_datasets(self) -> Callable[ - [data_labeling_service.ListDatasetsRequest], - Awaitable[data_labeling_service.ListDatasetsResponse]]: - r"""Return a callable for the list datasets method over gRPC. - - Lists datasets under a project. Pagination is - supported. - - Returns: - Callable[[~.ListDatasetsRequest], - Awaitable[~.ListDatasetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_datasets' not in self._stubs: - self._stubs['list_datasets'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDatasets', - request_serializer=data_labeling_service.ListDatasetsRequest.serialize, - response_deserializer=data_labeling_service.ListDatasetsResponse.deserialize, - ) - return self._stubs['list_datasets'] - - @property - def delete_dataset(self) -> Callable[ - [data_labeling_service.DeleteDatasetRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete dataset method over gRPC. - - Deletes a dataset by resource name. - - Returns: - Callable[[~.DeleteDatasetRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['delete_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteDataset', - request_serializer=data_labeling_service.DeleteDatasetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_dataset'] - - @property - def import_data(self) -> Callable[ - [data_labeling_service.ImportDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import data method over gRPC. - - Imports data into dataset based on source locations - defined in request. It can be called multiple times for - the same dataset. Each dataset can only have one long - running operation running on it. For example, no - labeling task (also long running operation) can be - started while importing is still ongoing. Vice versa. - - Returns: - Callable[[~.ImportDataRequest], - 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_data' not in self._stubs: - self._stubs['import_data'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ImportData', - request_serializer=data_labeling_service.ImportDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_data'] - - @property - def export_data(self) -> Callable[ - [data_labeling_service.ExportDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export data method over gRPC. - - Exports data and annotations from dataset. - - Returns: - Callable[[~.ExportDataRequest], - 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 'export_data' not in self._stubs: - self._stubs['export_data'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ExportData', - request_serializer=data_labeling_service.ExportDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_data'] - - @property - def get_data_item(self) -> Callable[ - [data_labeling_service.GetDataItemRequest], - Awaitable[dataset.DataItem]]: - r"""Return a callable for the get data item method over gRPC. - - Gets a data item in a dataset by resource name. This - API can be called after data are imported into dataset. - - Returns: - Callable[[~.GetDataItemRequest], - Awaitable[~.DataItem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_item' not in self._stubs: - self._stubs['get_data_item'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetDataItem', - request_serializer=data_labeling_service.GetDataItemRequest.serialize, - response_deserializer=dataset.DataItem.deserialize, - ) - return self._stubs['get_data_item'] - - @property - def list_data_items(self) -> Callable[ - [data_labeling_service.ListDataItemsRequest], - Awaitable[data_labeling_service.ListDataItemsResponse]]: - r"""Return a callable for the list data items method over gRPC. - - Lists data items in a dataset. This API can be called - after data are imported into dataset. Pagination is - supported. - - Returns: - Callable[[~.ListDataItemsRequest], - Awaitable[~.ListDataItemsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_items' not in self._stubs: - self._stubs['list_data_items'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListDataItems', - request_serializer=data_labeling_service.ListDataItemsRequest.serialize, - response_deserializer=data_labeling_service.ListDataItemsResponse.deserialize, - ) - return self._stubs['list_data_items'] - - @property - def get_annotated_dataset(self) -> Callable[ - [data_labeling_service.GetAnnotatedDatasetRequest], - Awaitable[dataset.AnnotatedDataset]]: - r"""Return a callable for the get annotated dataset method over gRPC. - - Gets an annotated dataset by resource name. - - Returns: - Callable[[~.GetAnnotatedDatasetRequest], - Awaitable[~.AnnotatedDataset]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: - self._stubs['get_annotated_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotatedDataset', - request_serializer=data_labeling_service.GetAnnotatedDatasetRequest.serialize, - response_deserializer=dataset.AnnotatedDataset.deserialize, - ) - return self._stubs['get_annotated_dataset'] - - @property - def list_annotated_datasets(self) -> Callable[ - [data_labeling_service.ListAnnotatedDatasetsRequest], - Awaitable[data_labeling_service.ListAnnotatedDatasetsResponse]]: - r"""Return a callable for the list annotated datasets method over gRPC. - - Lists annotated datasets for a dataset. Pagination is - supported. - - Returns: - Callable[[~.ListAnnotatedDatasetsRequest], - Awaitable[~.ListAnnotatedDatasetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotated_datasets' not in self._stubs: - self._stubs['list_annotated_datasets'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotatedDatasets', - request_serializer=data_labeling_service.ListAnnotatedDatasetsRequest.serialize, - response_deserializer=data_labeling_service.ListAnnotatedDatasetsResponse.deserialize, - ) - return self._stubs['list_annotated_datasets'] - - @property - def delete_annotated_dataset(self) -> Callable[ - [data_labeling_service.DeleteAnnotatedDatasetRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete annotated dataset method over gRPC. - - Deletes an annotated dataset by resource name. - - Returns: - Callable[[~.DeleteAnnotatedDatasetRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotated_dataset' not in self._stubs: - self._stubs['delete_annotated_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotatedDataset', - request_serializer=data_labeling_service.DeleteAnnotatedDatasetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_annotated_dataset'] - - @property - def label_image(self) -> Callable[ - [data_labeling_service.LabelImageRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the label image method over gRPC. - - Starts a labeling task for image. The type of image - labeling task is configured by feature in the request. - - Returns: - Callable[[~.LabelImageRequest], - 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 'label_image' not in self._stubs: - self._stubs['label_image'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelImage', - request_serializer=data_labeling_service.LabelImageRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['label_image'] - - @property - def label_video(self) -> Callable[ - [data_labeling_service.LabelVideoRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the label video method over gRPC. - - Starts a labeling task for video. The type of video - labeling task is configured by feature in the request. - - Returns: - Callable[[~.LabelVideoRequest], - 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 'label_video' not in self._stubs: - self._stubs['label_video'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelVideo', - request_serializer=data_labeling_service.LabelVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['label_video'] - - @property - def label_text(self) -> Callable[ - [data_labeling_service.LabelTextRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the label text method over gRPC. - - Starts a labeling task for text. The type of text - labeling task is configured by feature in the request. - - Returns: - Callable[[~.LabelTextRequest], - 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 'label_text' not in self._stubs: - self._stubs['label_text'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/LabelText', - request_serializer=data_labeling_service.LabelTextRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['label_text'] - - @property - def get_example(self) -> Callable[ - [data_labeling_service.GetExampleRequest], - Awaitable[dataset.Example]]: - r"""Return a callable for the get example method over gRPC. - - Gets an example by resource name, including both data - and annotation. - - Returns: - Callable[[~.GetExampleRequest], - Awaitable[~.Example]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_example' not in self._stubs: - self._stubs['get_example'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetExample', - request_serializer=data_labeling_service.GetExampleRequest.serialize, - response_deserializer=dataset.Example.deserialize, - ) - return self._stubs['get_example'] - - @property - def list_examples(self) -> Callable[ - [data_labeling_service.ListExamplesRequest], - Awaitable[data_labeling_service.ListExamplesResponse]]: - r"""Return a callable for the list examples method over gRPC. - - Lists examples in an annotated dataset. Pagination is - supported. - - Returns: - Callable[[~.ListExamplesRequest], - Awaitable[~.ListExamplesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_examples' not in self._stubs: - self._stubs['list_examples'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListExamples', - request_serializer=data_labeling_service.ListExamplesRequest.serialize, - response_deserializer=data_labeling_service.ListExamplesResponse.deserialize, - ) - return self._stubs['list_examples'] - - @property - def create_annotation_spec_set(self) -> Callable[ - [data_labeling_service.CreateAnnotationSpecSetRequest], - Awaitable[gcd_annotation_spec_set.AnnotationSpecSet]]: - r"""Return a callable for the create annotation spec set method over gRPC. - - Creates an annotation spec set by providing a set of - labels. - - Returns: - Callable[[~.CreateAnnotationSpecSetRequest], - Awaitable[~.AnnotationSpecSet]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: - self._stubs['create_annotation_spec_set'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateAnnotationSpecSet', - request_serializer=data_labeling_service.CreateAnnotationSpecSetRequest.serialize, - response_deserializer=gcd_annotation_spec_set.AnnotationSpecSet.deserialize, - ) - return self._stubs['create_annotation_spec_set'] - - @property - def get_annotation_spec_set(self) -> Callable[ - [data_labeling_service.GetAnnotationSpecSetRequest], - Awaitable[annotation_spec_set.AnnotationSpecSet]]: - r"""Return a callable for the get annotation spec set method over gRPC. - - Gets an annotation spec set by resource name. - - Returns: - Callable[[~.GetAnnotationSpecSetRequest], - Awaitable[~.AnnotationSpecSet]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: - self._stubs['get_annotation_spec_set'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetAnnotationSpecSet', - request_serializer=data_labeling_service.GetAnnotationSpecSetRequest.serialize, - response_deserializer=annotation_spec_set.AnnotationSpecSet.deserialize, - ) - return self._stubs['get_annotation_spec_set'] - - @property - def list_annotation_spec_sets(self) -> Callable[ - [data_labeling_service.ListAnnotationSpecSetsRequest], - Awaitable[data_labeling_service.ListAnnotationSpecSetsResponse]]: - r"""Return a callable for the list annotation spec sets method over gRPC. - - Lists annotation spec sets for a project. Pagination - is supported. - - Returns: - Callable[[~.ListAnnotationSpecSetsRequest], - Awaitable[~.ListAnnotationSpecSetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_sets' not in self._stubs: - self._stubs['list_annotation_spec_sets'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListAnnotationSpecSets', - request_serializer=data_labeling_service.ListAnnotationSpecSetsRequest.serialize, - response_deserializer=data_labeling_service.ListAnnotationSpecSetsResponse.deserialize, - ) - return self._stubs['list_annotation_spec_sets'] - - @property - def delete_annotation_spec_set(self) -> Callable[ - [data_labeling_service.DeleteAnnotationSpecSetRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete annotation spec set method over gRPC. - - Deletes an annotation spec set by resource name. - - Returns: - Callable[[~.DeleteAnnotationSpecSetRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_annotation_spec_set' not in self._stubs: - self._stubs['delete_annotation_spec_set'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteAnnotationSpecSet', - request_serializer=data_labeling_service.DeleteAnnotationSpecSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_annotation_spec_set'] - - @property - def create_instruction(self) -> Callable[ - [data_labeling_service.CreateInstructionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create instruction method over gRPC. - - Creates an instruction for how data should be - labeled. - - Returns: - Callable[[~.CreateInstructionRequest], - 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 'create_instruction' not in self._stubs: - self._stubs['create_instruction'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateInstruction', - request_serializer=data_labeling_service.CreateInstructionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_instruction'] - - @property - def get_instruction(self) -> Callable[ - [data_labeling_service.GetInstructionRequest], - Awaitable[instruction.Instruction]]: - r"""Return a callable for the get instruction method over gRPC. - - Gets an instruction by resource name. - - Returns: - Callable[[~.GetInstructionRequest], - Awaitable[~.Instruction]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instruction' not in self._stubs: - self._stubs['get_instruction'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetInstruction', - request_serializer=data_labeling_service.GetInstructionRequest.serialize, - response_deserializer=instruction.Instruction.deserialize, - ) - return self._stubs['get_instruction'] - - @property - def list_instructions(self) -> Callable[ - [data_labeling_service.ListInstructionsRequest], - Awaitable[data_labeling_service.ListInstructionsResponse]]: - r"""Return a callable for the list instructions method over gRPC. - - Lists instructions for a project. Pagination is - supported. - - Returns: - Callable[[~.ListInstructionsRequest], - Awaitable[~.ListInstructionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instructions' not in self._stubs: - self._stubs['list_instructions'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListInstructions', - request_serializer=data_labeling_service.ListInstructionsRequest.serialize, - response_deserializer=data_labeling_service.ListInstructionsResponse.deserialize, - ) - return self._stubs['list_instructions'] - - @property - def delete_instruction(self) -> Callable[ - [data_labeling_service.DeleteInstructionRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete instruction method over gRPC. - - Deletes an instruction object by resource name. - - Returns: - Callable[[~.DeleteInstructionRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instruction' not in self._stubs: - self._stubs['delete_instruction'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteInstruction', - request_serializer=data_labeling_service.DeleteInstructionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_instruction'] - - @property - def get_evaluation(self) -> Callable[ - [data_labeling_service.GetEvaluationRequest], - Awaitable[evaluation.Evaluation]]: - r"""Return a callable for the get evaluation method over gRPC. - - Gets an evaluation by resource name (to search, use - [projects.evaluations.search][google.cloud.datalabeling.v1beta1.DataLabelingService.SearchEvaluations]). - - 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.datalabeling.v1beta1.DataLabelingService/GetEvaluation', - request_serializer=data_labeling_service.GetEvaluationRequest.serialize, - response_deserializer=evaluation.Evaluation.deserialize, - ) - return self._stubs['get_evaluation'] - - @property - def search_evaluations(self) -> Callable[ - [data_labeling_service.SearchEvaluationsRequest], - Awaitable[data_labeling_service.SearchEvaluationsResponse]]: - r"""Return a callable for the search evaluations method over gRPC. - - Searches - [evaluations][google.cloud.datalabeling.v1beta1.Evaluation] - within a project. - - Returns: - Callable[[~.SearchEvaluationsRequest], - Awaitable[~.SearchEvaluationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_evaluations' not in self._stubs: - self._stubs['search_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchEvaluations', - request_serializer=data_labeling_service.SearchEvaluationsRequest.serialize, - response_deserializer=data_labeling_service.SearchEvaluationsResponse.deserialize, - ) - return self._stubs['search_evaluations'] - - @property - def search_example_comparisons(self) -> Callable[ - [data_labeling_service.SearchExampleComparisonsRequest], - Awaitable[data_labeling_service.SearchExampleComparisonsResponse]]: - r"""Return a callable for the search example comparisons method over gRPC. - - Searches example comparisons from an evaluation. The - return format is a list of example comparisons that show - ground truth and prediction(s) for a single input. - Search by providing an evaluation ID. - - Returns: - Callable[[~.SearchExampleComparisonsRequest], - Awaitable[~.SearchExampleComparisonsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_example_comparisons' not in self._stubs: - self._stubs['search_example_comparisons'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/SearchExampleComparisons', - request_serializer=data_labeling_service.SearchExampleComparisonsRequest.serialize, - response_deserializer=data_labeling_service.SearchExampleComparisonsResponse.deserialize, - ) - return self._stubs['search_example_comparisons'] - - @property - def create_evaluation_job(self) -> Callable[ - [data_labeling_service.CreateEvaluationJobRequest], - Awaitable[evaluation_job.EvaluationJob]]: - r"""Return a callable for the create evaluation job method over gRPC. - - Creates an evaluation job. - - Returns: - Callable[[~.CreateEvaluationJobRequest], - Awaitable[~.EvaluationJob]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: - self._stubs['create_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/CreateEvaluationJob', - request_serializer=data_labeling_service.CreateEvaluationJobRequest.serialize, - response_deserializer=evaluation_job.EvaluationJob.deserialize, - ) - return self._stubs['create_evaluation_job'] - - @property - def update_evaluation_job(self) -> Callable[ - [data_labeling_service.UpdateEvaluationJobRequest], - Awaitable[gcd_evaluation_job.EvaluationJob]]: - r"""Return a callable for the update evaluation job method over gRPC. - - Updates an evaluation job. You can only update certain fields of - the job's - [EvaluationJobConfig][google.cloud.datalabeling.v1beta1.EvaluationJobConfig]: - ``humanAnnotationConfig.instruction``, ``exampleCount``, and - ``exampleSamplePercentage``. - - If you want to change any other aspect of the evaluation job, - you must delete the job and create a new one. - - Returns: - Callable[[~.UpdateEvaluationJobRequest], - Awaitable[~.EvaluationJob]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: - self._stubs['update_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/UpdateEvaluationJob', - request_serializer=data_labeling_service.UpdateEvaluationJobRequest.serialize, - response_deserializer=gcd_evaluation_job.EvaluationJob.deserialize, - ) - return self._stubs['update_evaluation_job'] - - @property - def get_evaluation_job(self) -> Callable[ - [data_labeling_service.GetEvaluationJobRequest], - Awaitable[evaluation_job.EvaluationJob]]: - r"""Return a callable for the get evaluation job method over gRPC. - - Gets an evaluation job by resource name. - - Returns: - Callable[[~.GetEvaluationJobRequest], - Awaitable[~.EvaluationJob]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_job' not in self._stubs: - self._stubs['get_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/GetEvaluationJob', - request_serializer=data_labeling_service.GetEvaluationJobRequest.serialize, - response_deserializer=evaluation_job.EvaluationJob.deserialize, - ) - return self._stubs['get_evaluation_job'] - - @property - def pause_evaluation_job(self) -> Callable[ - [data_labeling_service.PauseEvaluationJobRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the pause evaluation job method over gRPC. - - Pauses an evaluation job. Pausing an evaluation job that is - already in a ``PAUSED`` state is a no-op. - - Returns: - Callable[[~.PauseEvaluationJobRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'pause_evaluation_job' not in self._stubs: - self._stubs['pause_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/PauseEvaluationJob', - request_serializer=data_labeling_service.PauseEvaluationJobRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['pause_evaluation_job'] - - @property - def resume_evaluation_job(self) -> Callable[ - [data_labeling_service.ResumeEvaluationJobRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the resume evaluation job method over gRPC. - - Resumes a paused evaluation job. A deleted evaluation - job can't be resumed. Resuming a running or scheduled - evaluation job is a no-op. - - Returns: - Callable[[~.ResumeEvaluationJobRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'resume_evaluation_job' not in self._stubs: - self._stubs['resume_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ResumeEvaluationJob', - request_serializer=data_labeling_service.ResumeEvaluationJobRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['resume_evaluation_job'] - - @property - def delete_evaluation_job(self) -> Callable[ - [data_labeling_service.DeleteEvaluationJobRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete evaluation job method over gRPC. - - Stops and deletes an evaluation job. - - Returns: - Callable[[~.DeleteEvaluationJobRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_job' not in self._stubs: - self._stubs['delete_evaluation_job'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/DeleteEvaluationJob', - request_serializer=data_labeling_service.DeleteEvaluationJobRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_evaluation_job'] - - @property - def list_evaluation_jobs(self) -> Callable[ - [data_labeling_service.ListEvaluationJobsRequest], - Awaitable[data_labeling_service.ListEvaluationJobsResponse]]: - r"""Return a callable for the list evaluation jobs method over gRPC. - - Lists all evaluation jobs within a project with - possible filters. Pagination is supported. - - Returns: - Callable[[~.ListEvaluationJobsRequest], - Awaitable[~.ListEvaluationJobsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_evaluation_jobs' not in self._stubs: - self._stubs['list_evaluation_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.datalabeling.v1beta1.DataLabelingService/ListEvaluationJobs', - request_serializer=data_labeling_service.ListEvaluationJobsRequest.serialize, - response_deserializer=data_labeling_service.ListEvaluationJobsResponse.deserialize, - ) - return self._stubs['list_evaluation_jobs'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'DataLabelingServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py deleted file mode 100644 index 1baffe3..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/__init__.py +++ /dev/null @@ -1,308 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .annotation import ( - Annotation, - AnnotationMetadata, - AnnotationValue, - BoundingPoly, - ImageBoundingPolyAnnotation, - ImageClassificationAnnotation, - ImagePolylineAnnotation, - ImageSegmentationAnnotation, - NormalizedBoundingPoly, - NormalizedPolyline, - NormalizedVertex, - ObjectTrackingFrame, - OperatorMetadata, - Polyline, - SequentialSegment, - TextClassificationAnnotation, - TextEntityExtractionAnnotation, - TimeSegment, - Vertex, - VideoClassificationAnnotation, - VideoEventAnnotation, - VideoObjectTrackingAnnotation, - AnnotationSentiment, - AnnotationSource, - AnnotationType, -) -from .annotation_spec_set import ( - AnnotationSpec, - AnnotationSpecSet, -) -from .data_labeling_service import ( - CreateAnnotationSpecSetRequest, - CreateDatasetRequest, - CreateEvaluationJobRequest, - CreateInstructionRequest, - DeleteAnnotatedDatasetRequest, - DeleteAnnotationSpecSetRequest, - DeleteDatasetRequest, - DeleteEvaluationJobRequest, - DeleteInstructionRequest, - ExportDataRequest, - GetAnnotatedDatasetRequest, - GetAnnotationSpecSetRequest, - GetDataItemRequest, - GetDatasetRequest, - GetEvaluationJobRequest, - GetEvaluationRequest, - GetExampleRequest, - GetInstructionRequest, - ImportDataRequest, - LabelImageRequest, - LabelTextRequest, - LabelVideoRequest, - ListAnnotatedDatasetsRequest, - ListAnnotatedDatasetsResponse, - ListAnnotationSpecSetsRequest, - ListAnnotationSpecSetsResponse, - ListDataItemsRequest, - ListDataItemsResponse, - ListDatasetsRequest, - ListDatasetsResponse, - ListEvaluationJobsRequest, - ListEvaluationJobsResponse, - ListExamplesRequest, - ListExamplesResponse, - ListInstructionsRequest, - ListInstructionsResponse, - PauseEvaluationJobRequest, - ResumeEvaluationJobRequest, - SearchEvaluationsRequest, - SearchEvaluationsResponse, - SearchExampleComparisonsRequest, - SearchExampleComparisonsResponse, - UpdateEvaluationJobRequest, -) -from .data_payloads import ( - ImagePayload, - TextPayload, - VideoPayload, - VideoThumbnail, -) -from .dataset import ( - AnnotatedDataset, - AnnotatedDatasetMetadata, - BigQuerySource, - ClassificationMetadata, - DataItem, - Dataset, - Example, - GcsDestination, - GcsFolderDestination, - GcsSource, - InputConfig, - LabelStats, - OutputConfig, - TextMetadata, - DataType, -) -from .evaluation import ( - BoundingBoxEvaluationOptions, - ClassificationMetrics, - ConfusionMatrix, - Evaluation, - EvaluationConfig, - EvaluationMetrics, - ObjectDetectionMetrics, - PrCurve, -) -from .evaluation_job import ( - Attempt, - EvaluationJob, - EvaluationJobAlertConfig, - EvaluationJobConfig, -) -from .human_annotation_config import ( - BoundingPolyConfig, - EventConfig, - HumanAnnotationConfig, - ImageClassificationConfig, - ObjectDetectionConfig, - ObjectTrackingConfig, - PolylineConfig, - SegmentationConfig, - SentimentConfig, - TextClassificationConfig, - TextEntityExtractionConfig, - VideoClassificationConfig, - StringAggregationType, -) -from .instruction import ( - CsvInstruction, - Instruction, - PdfInstruction, -) -from .operations import ( - CreateInstructionMetadata, - ExportDataOperationMetadata, - ExportDataOperationResponse, - ImportDataOperationMetadata, - ImportDataOperationResponse, - LabelImageBoundingBoxOperationMetadata, - LabelImageBoundingPolyOperationMetadata, - LabelImageClassificationOperationMetadata, - LabelImageOrientedBoundingBoxOperationMetadata, - LabelImagePolylineOperationMetadata, - LabelImageSegmentationOperationMetadata, - LabelOperationMetadata, - LabelTextClassificationOperationMetadata, - LabelTextEntityExtractionOperationMetadata, - LabelVideoClassificationOperationMetadata, - LabelVideoEventOperationMetadata, - LabelVideoObjectDetectionOperationMetadata, - LabelVideoObjectTrackingOperationMetadata, -) - -__all__ = ( - 'Annotation', - 'AnnotationMetadata', - 'AnnotationValue', - 'BoundingPoly', - 'ImageBoundingPolyAnnotation', - 'ImageClassificationAnnotation', - 'ImagePolylineAnnotation', - 'ImageSegmentationAnnotation', - 'NormalizedBoundingPoly', - 'NormalizedPolyline', - 'NormalizedVertex', - 'ObjectTrackingFrame', - 'OperatorMetadata', - 'Polyline', - 'SequentialSegment', - 'TextClassificationAnnotation', - 'TextEntityExtractionAnnotation', - 'TimeSegment', - 'Vertex', - 'VideoClassificationAnnotation', - 'VideoEventAnnotation', - 'VideoObjectTrackingAnnotation', - 'AnnotationSentiment', - 'AnnotationSource', - 'AnnotationType', - 'AnnotationSpec', - 'AnnotationSpecSet', - 'CreateAnnotationSpecSetRequest', - 'CreateDatasetRequest', - 'CreateEvaluationJobRequest', - 'CreateInstructionRequest', - 'DeleteAnnotatedDatasetRequest', - 'DeleteAnnotationSpecSetRequest', - 'DeleteDatasetRequest', - 'DeleteEvaluationJobRequest', - 'DeleteInstructionRequest', - 'ExportDataRequest', - 'GetAnnotatedDatasetRequest', - 'GetAnnotationSpecSetRequest', - 'GetDataItemRequest', - 'GetDatasetRequest', - 'GetEvaluationJobRequest', - 'GetEvaluationRequest', - 'GetExampleRequest', - 'GetInstructionRequest', - 'ImportDataRequest', - 'LabelImageRequest', - 'LabelTextRequest', - 'LabelVideoRequest', - 'ListAnnotatedDatasetsRequest', - 'ListAnnotatedDatasetsResponse', - 'ListAnnotationSpecSetsRequest', - 'ListAnnotationSpecSetsResponse', - 'ListDataItemsRequest', - 'ListDataItemsResponse', - 'ListDatasetsRequest', - 'ListDatasetsResponse', - 'ListEvaluationJobsRequest', - 'ListEvaluationJobsResponse', - 'ListExamplesRequest', - 'ListExamplesResponse', - 'ListInstructionsRequest', - 'ListInstructionsResponse', - 'PauseEvaluationJobRequest', - 'ResumeEvaluationJobRequest', - 'SearchEvaluationsRequest', - 'SearchEvaluationsResponse', - 'SearchExampleComparisonsRequest', - 'SearchExampleComparisonsResponse', - 'UpdateEvaluationJobRequest', - 'ImagePayload', - 'TextPayload', - 'VideoPayload', - 'VideoThumbnail', - 'AnnotatedDataset', - 'AnnotatedDatasetMetadata', - 'BigQuerySource', - 'ClassificationMetadata', - 'DataItem', - 'Dataset', - 'Example', - 'GcsDestination', - 'GcsFolderDestination', - 'GcsSource', - 'InputConfig', - 'LabelStats', - 'OutputConfig', - 'TextMetadata', - 'DataType', - 'BoundingBoxEvaluationOptions', - 'ClassificationMetrics', - 'ConfusionMatrix', - 'Evaluation', - 'EvaluationConfig', - 'EvaluationMetrics', - 'ObjectDetectionMetrics', - 'PrCurve', - 'Attempt', - 'EvaluationJob', - 'EvaluationJobAlertConfig', - 'EvaluationJobConfig', - 'BoundingPolyConfig', - 'EventConfig', - 'HumanAnnotationConfig', - 'ImageClassificationConfig', - 'ObjectDetectionConfig', - 'ObjectTrackingConfig', - 'PolylineConfig', - 'SegmentationConfig', - 'SentimentConfig', - 'TextClassificationConfig', - 'TextEntityExtractionConfig', - 'VideoClassificationConfig', - 'StringAggregationType', - 'CsvInstruction', - 'Instruction', - 'PdfInstruction', - 'CreateInstructionMetadata', - 'ExportDataOperationMetadata', - 'ExportDataOperationResponse', - 'ImportDataOperationMetadata', - 'ImportDataOperationResponse', - 'LabelImageBoundingBoxOperationMetadata', - 'LabelImageBoundingPolyOperationMetadata', - 'LabelImageClassificationOperationMetadata', - 'LabelImageOrientedBoundingBoxOperationMetadata', - 'LabelImagePolylineOperationMetadata', - 'LabelImageSegmentationOperationMetadata', - 'LabelOperationMetadata', - 'LabelTextClassificationOperationMetadata', - 'LabelTextEntityExtractionOperationMetadata', - 'LabelVideoClassificationOperationMetadata', - 'LabelVideoEventOperationMetadata', - 'LabelVideoObjectDetectionOperationMetadata', - 'LabelVideoObjectTrackingOperationMetadata', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py deleted file mode 100644 index 1b3a8a5..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation.py +++ /dev/null @@ -1,688 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'AnnotationSource', - 'AnnotationSentiment', - 'AnnotationType', - 'Annotation', - 'AnnotationValue', - 'ImageClassificationAnnotation', - 'Vertex', - 'NormalizedVertex', - 'BoundingPoly', - 'NormalizedBoundingPoly', - 'ImageBoundingPolyAnnotation', - 'Polyline', - 'NormalizedPolyline', - 'ImagePolylineAnnotation', - 'ImageSegmentationAnnotation', - 'TextClassificationAnnotation', - 'TextEntityExtractionAnnotation', - 'SequentialSegment', - 'TimeSegment', - 'VideoClassificationAnnotation', - 'ObjectTrackingFrame', - 'VideoObjectTrackingAnnotation', - 'VideoEventAnnotation', - 'AnnotationMetadata', - 'OperatorMetadata', - }, -) - - -class AnnotationSource(proto.Enum): - r"""Specifies where the annotation comes from (whether it was - provided by a human labeler or a different source). - """ - ANNOTATION_SOURCE_UNSPECIFIED = 0 - OPERATOR = 3 - - -class AnnotationSentiment(proto.Enum): - r"""""" - ANNOTATION_SENTIMENT_UNSPECIFIED = 0 - NEGATIVE = 1 - POSITIVE = 2 - - -class AnnotationType(proto.Enum): - r"""""" - ANNOTATION_TYPE_UNSPECIFIED = 0 - IMAGE_CLASSIFICATION_ANNOTATION = 1 - IMAGE_BOUNDING_BOX_ANNOTATION = 2 - IMAGE_ORIENTED_BOUNDING_BOX_ANNOTATION = 13 - IMAGE_BOUNDING_POLY_ANNOTATION = 10 - IMAGE_POLYLINE_ANNOTATION = 11 - IMAGE_SEGMENTATION_ANNOTATION = 12 - VIDEO_SHOTS_CLASSIFICATION_ANNOTATION = 3 - VIDEO_OBJECT_TRACKING_ANNOTATION = 4 - VIDEO_OBJECT_DETECTION_ANNOTATION = 5 - VIDEO_EVENT_ANNOTATION = 6 - TEXT_CLASSIFICATION_ANNOTATION = 8 - TEXT_ENTITY_EXTRACTION_ANNOTATION = 9 - GENERAL_CLASSIFICATION_ANNOTATION = 14 - - -class Annotation(proto.Message): - r"""Annotation for Example. Each example may have one or more - annotations. For example in image classification problem, each - image might have one or more labels. We call labels binded with - this image an Annotation. - - Attributes: - name (str): - Output only. Unique name of this annotation, format is: - - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/{annotated_dataset}/examples/{example_id}/annotations/{annotation_id} - annotation_source (google.cloud.datalabeling_v1beta1.types.AnnotationSource): - Output only. The source of the annotation. - annotation_value (google.cloud.datalabeling_v1beta1.types.AnnotationValue): - Output only. This is the actual annotation - value, e.g classification, bounding box values - are stored here. - annotation_metadata (google.cloud.datalabeling_v1beta1.types.AnnotationMetadata): - Output only. Annotation metadata, including - information like votes for labels. - annotation_sentiment (google.cloud.datalabeling_v1beta1.types.AnnotationSentiment): - Output only. Sentiment for this annotation. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - annotation_source = proto.Field( - proto.ENUM, - number=2, - enum='AnnotationSource', - ) - annotation_value = proto.Field( - proto.MESSAGE, - number=3, - message='AnnotationValue', - ) - annotation_metadata = proto.Field( - proto.MESSAGE, - number=4, - message='AnnotationMetadata', - ) - annotation_sentiment = proto.Field( - proto.ENUM, - number=6, - enum='AnnotationSentiment', - ) - - -class AnnotationValue(proto.Message): - r"""Annotation value for an example. - - Attributes: - image_classification_annotation (google.cloud.datalabeling_v1beta1.types.ImageClassificationAnnotation): - Annotation value for image classification - case. - image_bounding_poly_annotation (google.cloud.datalabeling_v1beta1.types.ImageBoundingPolyAnnotation): - Annotation value for image bounding box, - oriented bounding box and polygon cases. - image_polyline_annotation (google.cloud.datalabeling_v1beta1.types.ImagePolylineAnnotation): - Annotation value for image polyline cases. - Polyline here is different from BoundingPoly. It - is formed by line segments connected to each - other but not closed form(Bounding Poly). The - line segments can cross each other. - image_segmentation_annotation (google.cloud.datalabeling_v1beta1.types.ImageSegmentationAnnotation): - Annotation value for image segmentation. - text_classification_annotation (google.cloud.datalabeling_v1beta1.types.TextClassificationAnnotation): - Annotation value for text classification - case. - text_entity_extraction_annotation (google.cloud.datalabeling_v1beta1.types.TextEntityExtractionAnnotation): - Annotation value for text entity extraction - case. - video_classification_annotation (google.cloud.datalabeling_v1beta1.types.VideoClassificationAnnotation): - Annotation value for video classification - case. - video_object_tracking_annotation (google.cloud.datalabeling_v1beta1.types.VideoObjectTrackingAnnotation): - Annotation value for video object detection - and tracking case. - video_event_annotation (google.cloud.datalabeling_v1beta1.types.VideoEventAnnotation): - Annotation value for video event case. - """ - - image_classification_annotation = proto.Field( - proto.MESSAGE, - number=1, - oneof='value_type', - message='ImageClassificationAnnotation', - ) - image_bounding_poly_annotation = proto.Field( - proto.MESSAGE, - number=2, - oneof='value_type', - message='ImageBoundingPolyAnnotation', - ) - image_polyline_annotation = proto.Field( - proto.MESSAGE, - number=8, - oneof='value_type', - message='ImagePolylineAnnotation', - ) - image_segmentation_annotation = proto.Field( - proto.MESSAGE, - number=9, - oneof='value_type', - message='ImageSegmentationAnnotation', - ) - text_classification_annotation = proto.Field( - proto.MESSAGE, - number=3, - oneof='value_type', - message='TextClassificationAnnotation', - ) - text_entity_extraction_annotation = proto.Field( - proto.MESSAGE, - number=10, - oneof='value_type', - message='TextEntityExtractionAnnotation', - ) - video_classification_annotation = proto.Field( - proto.MESSAGE, - number=4, - oneof='value_type', - message='VideoClassificationAnnotation', - ) - video_object_tracking_annotation = proto.Field( - proto.MESSAGE, - number=5, - oneof='value_type', - message='VideoObjectTrackingAnnotation', - ) - video_event_annotation = proto.Field( - proto.MESSAGE, - number=6, - oneof='value_type', - message='VideoEventAnnotation', - ) - - -class ImageClassificationAnnotation(proto.Message): - r"""Image classification annotation definition. - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of image. - """ - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - - -class Vertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the vertex coordinates are in the same scale as the - original image. - - Attributes: - x (int): - X coordinate. - y (int): - Y coordinate. - """ - - x = proto.Field( - proto.INT32, - number=1, - ) - y = proto.Field( - proto.INT32, - number=2, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate. - """ - - x = proto.Field( - proto.FLOAT, - number=1, - ) - y = proto.Field( - proto.FLOAT, - number=2, - ) - - -class BoundingPoly(proto.Message): - r"""A bounding polygon in the image. - - Attributes: - vertices (Sequence[google.cloud.datalabeling_v1beta1.types.Vertex]): - The bounding polygon vertices. - """ - - vertices = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - - -class NormalizedBoundingPoly(proto.Message): - r"""Normalized bounding polygon. - - Attributes: - normalized_vertices (Sequence[google.cloud.datalabeling_v1beta1.types.NormalizedVertex]): - The bounding polygon normalized vertices. - """ - - normalized_vertices = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NormalizedVertex', - ) - - -class ImageBoundingPolyAnnotation(proto.Message): - r"""Image bounding poly annotation. It represents a polygon - including bounding box in the image. - - Attributes: - bounding_poly (google.cloud.datalabeling_v1beta1.types.BoundingPoly): - - normalized_bounding_poly (google.cloud.datalabeling_v1beta1.types.NormalizedBoundingPoly): - - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of object in this bounding polygon. - """ - - bounding_poly = proto.Field( - proto.MESSAGE, - number=2, - oneof='bounded_area', - message='BoundingPoly', - ) - normalized_bounding_poly = proto.Field( - proto.MESSAGE, - number=3, - oneof='bounded_area', - message='NormalizedBoundingPoly', - ) - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - - -class Polyline(proto.Message): - r"""A line with multiple line segments. - - Attributes: - vertices (Sequence[google.cloud.datalabeling_v1beta1.types.Vertex]): - The polyline vertices. - """ - - vertices = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Vertex', - ) - - -class NormalizedPolyline(proto.Message): - r"""Normalized polyline. - - Attributes: - normalized_vertices (Sequence[google.cloud.datalabeling_v1beta1.types.NormalizedVertex]): - The normalized polyline vertices. - """ - - normalized_vertices = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NormalizedVertex', - ) - - -class ImagePolylineAnnotation(proto.Message): - r"""A polyline for the image annotation. - - Attributes: - polyline (google.cloud.datalabeling_v1beta1.types.Polyline): - - normalized_polyline (google.cloud.datalabeling_v1beta1.types.NormalizedPolyline): - - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of this polyline. - """ - - polyline = proto.Field( - proto.MESSAGE, - number=2, - oneof='poly', - message='Polyline', - ) - normalized_polyline = proto.Field( - proto.MESSAGE, - number=3, - oneof='poly', - message='NormalizedPolyline', - ) - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - - -class ImageSegmentationAnnotation(proto.Message): - r"""Image segmentation annotation. - - Attributes: - annotation_colors (Sequence[google.cloud.datalabeling_v1beta1.types.ImageSegmentationAnnotation.AnnotationColorsEntry]): - The mapping between rgb color and annotation - spec. The key is the rgb color represented in - format of rgb(0, 0, 0). The value is the - AnnotationSpec. - mime_type (str): - Image format. - image_bytes (bytes): - A byte string of a full image's color map. - """ - - annotation_colors = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - mime_type = proto.Field( - proto.STRING, - number=2, - ) - image_bytes = proto.Field( - proto.BYTES, - number=3, - ) - - -class TextClassificationAnnotation(proto.Message): - r"""Text classification annotation. - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of the text. - """ - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - - -class TextEntityExtractionAnnotation(proto.Message): - r"""Text entity extraction annotation. - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of the text entities. - sequential_segment (google.cloud.datalabeling_v1beta1.types.SequentialSegment): - Position of the entity. - """ - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - sequential_segment = proto.Field( - proto.MESSAGE, - number=2, - message='SequentialSegment', - ) - - -class SequentialSegment(proto.Message): - r"""Start and end position in a sequence (e.g. text segment). - - Attributes: - start (int): - Start position (inclusive). - end (int): - End position (exclusive). - """ - - start = proto.Field( - proto.INT32, - number=1, - ) - end = proto.Field( - proto.INT32, - number=2, - ) - - -class TimeSegment(proto.Message): - r"""A time period inside of an example that has a time dimension - (e.g. video). - - Attributes: - start_time_offset (google.protobuf.duration_pb2.Duration): - Start of the time segment (inclusive), - represented as the duration since the example - start. - end_time_offset (google.protobuf.duration_pb2.Duration): - End of the time segment (exclusive), - represented as the duration since the example - start. - """ - - start_time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class VideoClassificationAnnotation(proto.Message): - r"""Video classification annotation. - - Attributes: - time_segment (google.cloud.datalabeling_v1beta1.types.TimeSegment): - The time segment of the video to which the - annotation applies. - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of the segment specified by time_segment. - """ - - time_segment = proto.Field( - proto.MESSAGE, - number=1, - message='TimeSegment', - ) - annotation_spec = proto.Field( - proto.MESSAGE, - number=2, - message=annotation_spec_set.AnnotationSpec, - ) - - -class ObjectTrackingFrame(proto.Message): - r"""Video frame level annotation for object detection and - tracking. - - Attributes: - bounding_poly (google.cloud.datalabeling_v1beta1.types.BoundingPoly): - - normalized_bounding_poly (google.cloud.datalabeling_v1beta1.types.NormalizedBoundingPoly): - - time_offset (google.protobuf.duration_pb2.Duration): - The time offset of this frame relative to the - beginning of the video. - """ - - bounding_poly = proto.Field( - proto.MESSAGE, - number=1, - oneof='bounded_area', - message='BoundingPoly', - ) - normalized_bounding_poly = proto.Field( - proto.MESSAGE, - number=2, - oneof='bounded_area', - message='NormalizedBoundingPoly', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - -class VideoObjectTrackingAnnotation(proto.Message): - r"""Video object tracking annotation. - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of the object tracked in this - annotation. - time_segment (google.cloud.datalabeling_v1beta1.types.TimeSegment): - The time segment of the video to which object - tracking applies. - object_tracking_frames (Sequence[google.cloud.datalabeling_v1beta1.types.ObjectTrackingFrame]): - The list of frames where this object track - appears. - """ - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - time_segment = proto.Field( - proto.MESSAGE, - number=2, - message='TimeSegment', - ) - object_tracking_frames = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='ObjectTrackingFrame', - ) - - -class VideoEventAnnotation(proto.Message): - r"""Video event annotation. - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - Label of the event in this annotation. - time_segment (google.cloud.datalabeling_v1beta1.types.TimeSegment): - The time segment of the video to which the - annotation applies. - """ - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - time_segment = proto.Field( - proto.MESSAGE, - number=2, - message='TimeSegment', - ) - - -class AnnotationMetadata(proto.Message): - r"""Additional information associated with the annotation. - - Attributes: - operator_metadata (google.cloud.datalabeling_v1beta1.types.OperatorMetadata): - Metadata related to human labeling. - """ - - operator_metadata = proto.Field( - proto.MESSAGE, - number=2, - message='OperatorMetadata', - ) - - -class OperatorMetadata(proto.Message): - r"""General information useful for labels coming from - contributors. - - Attributes: - score (float): - Confidence score corresponding to a label. - For examle, if 3 contributors have answered the - question and 2 of them agree on the final label, - the confidence score will be 0.67 (2/3). - total_votes (int): - The total number of contributors that answer - this question. - label_votes (int): - The total number of contributors that choose - this label. - comments (Sequence[str]): - Comments from contributors. - """ - - score = proto.Field( - proto.FLOAT, - number=1, - ) - total_votes = proto.Field( - proto.INT32, - number=2, - ) - label_votes = proto.Field( - proto.INT32, - number=3, - ) - comments = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py deleted file mode 100644 index bd887bc..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/annotation_spec_set.py +++ /dev/null @@ -1,108 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'AnnotationSpecSet', - 'AnnotationSpec', - }, -) - - -class AnnotationSpecSet(proto.Message): - r"""An AnnotationSpecSet is a collection of label definitions. - For example, in image classification tasks, you define a set of - possible labels for images as an AnnotationSpecSet. An - AnnotationSpecSet is immutable upon creation. - - Attributes: - name (str): - Output only. The AnnotationSpecSet resource name in the - following format: - - "projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}". - display_name (str): - Required. The display name for - AnnotationSpecSet that you define when you - create it. Maximum of 64 characters. - description (str): - Optional. User-provided description of the - annotation specification set. The description - can be up to 10,000 characters long. - annotation_specs (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotationSpec]): - Required. The array of AnnotationSpecs that - you define when you create the - AnnotationSpecSet. These are the possible labels - for the labeling task. - blocking_resources (Sequence[str]): - Output only. The names of any related - resources that are blocking changes to the - annotation spec set. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - annotation_specs = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AnnotationSpec', - ) - blocking_resources = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class AnnotationSpec(proto.Message): - r"""Container of information related to one possible annotation that can - be used in a labeling task. For example, an image classification - task where images are labeled as ``dog`` or ``cat`` must reference - an AnnotationSpec for ``dog`` and an AnnotationSpec for ``cat``. - - Attributes: - display_name (str): - Required. The display name of the - AnnotationSpec. Maximum of 64 characters. - description (str): - Optional. User-provided description of the - annotation specification. The description can be - up to 10,000 characters long. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py deleted file mode 100644 index e22ec3c..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_labeling_service.py +++ /dev/null @@ -1,1375 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job -from google.cloud.datalabeling_v1beta1.types import human_annotation_config -from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'CreateDatasetRequest', - 'GetDatasetRequest', - 'ListDatasetsRequest', - 'ListDatasetsResponse', - 'DeleteDatasetRequest', - 'ImportDataRequest', - 'ExportDataRequest', - 'GetDataItemRequest', - 'ListDataItemsRequest', - 'ListDataItemsResponse', - 'GetAnnotatedDatasetRequest', - 'ListAnnotatedDatasetsRequest', - 'ListAnnotatedDatasetsResponse', - 'DeleteAnnotatedDatasetRequest', - 'LabelImageRequest', - 'LabelVideoRequest', - 'LabelTextRequest', - 'GetExampleRequest', - 'ListExamplesRequest', - 'ListExamplesResponse', - 'CreateAnnotationSpecSetRequest', - 'GetAnnotationSpecSetRequest', - 'ListAnnotationSpecSetsRequest', - 'ListAnnotationSpecSetsResponse', - 'DeleteAnnotationSpecSetRequest', - 'CreateInstructionRequest', - 'GetInstructionRequest', - 'DeleteInstructionRequest', - 'ListInstructionsRequest', - 'ListInstructionsResponse', - 'GetEvaluationRequest', - 'SearchEvaluationsRequest', - 'SearchEvaluationsResponse', - 'SearchExampleComparisonsRequest', - 'SearchExampleComparisonsResponse', - 'CreateEvaluationJobRequest', - 'UpdateEvaluationJobRequest', - 'GetEvaluationJobRequest', - 'PauseEvaluationJobRequest', - 'ResumeEvaluationJobRequest', - 'DeleteEvaluationJobRequest', - 'ListEvaluationJobsRequest', - 'ListEvaluationJobsResponse', - }, -) - - -class CreateDatasetRequest(proto.Message): - r"""Request message for CreateDataset. - - Attributes: - parent (str): - Required. Dataset resource parent, format: - projects/{project_id} - dataset (google.cloud.datalabeling_v1beta1.types.Dataset): - Required. The dataset to be created. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - dataset = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_dataset.Dataset, - ) - - -class GetDatasetRequest(proto.Message): - r"""Request message for GetDataSet. - - Attributes: - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDatasetsRequest(proto.Message): - r"""Request message for ListDataset. - - Attributes: - parent (str): - Required. Dataset resource parent, format: - projects/{project_id} - filter (str): - Optional. Filter on dataset is not supported - at this moment. - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by - [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] - of the previous [DataLabelingService.ListDatasets] call. - Returns the first page if empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListDatasetsResponse(proto.Message): - r"""Results of listing datasets within a project. - - Attributes: - datasets (Sequence[google.cloud.datalabeling_v1beta1.types.Dataset]): - The list of datasets to return. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - datasets = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_dataset.Dataset, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteDatasetRequest(proto.Message): - r"""Request message for DeleteDataset. - - Attributes: - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ImportDataRequest(proto.Message): - r"""Request message for ImportData API. - - Attributes: - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - input_config (google.cloud.datalabeling_v1beta1.types.InputConfig): - Required. Specify the input source of the - data. - user_email_address (str): - Email of the user who started the import task - and should be notified by email. If empty no - notification will be sent. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_dataset.InputConfig, - ) - user_email_address = proto.Field( - proto.STRING, - number=3, - ) - - -class ExportDataRequest(proto.Message): - r"""Request message for ExportData API. - - Attributes: - name (str): - Required. Dataset resource name, format: - projects/{project_id}/datasets/{dataset_id} - annotated_dataset (str): - Required. Annotated dataset resource name. DataItem in - Dataset and their annotations in specified annotated dataset - will be exported. It's in format of - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - filter (str): - Optional. Filter is not supported at this - moment. - output_config (google.cloud.datalabeling_v1beta1.types.OutputConfig): - Required. Specify the output destination. - user_email_address (str): - Email of the user who started the export task - and should be notified by email. If empty no - notification will be sent. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - annotated_dataset = proto.Field( - proto.STRING, - number=2, - ) - filter = proto.Field( - proto.STRING, - number=3, - ) - output_config = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_dataset.OutputConfig, - ) - user_email_address = proto.Field( - proto.STRING, - number=5, - ) - - -class GetDataItemRequest(proto.Message): - r"""Request message for GetDataItem. - - Attributes: - name (str): - Required. The name of the data item to get, format: - projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDataItemsRequest(proto.Message): - r"""Request message for ListDataItems. - - Attributes: - parent (str): - Required. Name of the dataset to list data items, format: - projects/{project_id}/datasets/{dataset_id} - filter (str): - Optional. Filter is not supported at this - moment. - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by - [ListDataItemsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDataItemsResponse.next_page_token] - of the previous [DataLabelingService.ListDataItems] call. - Return first page if empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListDataItemsResponse(proto.Message): - r"""Results of listing data items in a dataset. - - Attributes: - data_items (Sequence[google.cloud.datalabeling_v1beta1.types.DataItem]): - The list of data items to return. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - data_items = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_dataset.DataItem, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetAnnotatedDatasetRequest(proto.Message): - r"""Request message for GetAnnotatedDataset. - - Attributes: - name (str): - Required. Name of the annotated dataset to get, format: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAnnotatedDatasetsRequest(proto.Message): - r"""Request message for ListAnnotatedDatasets. - - Attributes: - parent (str): - Required. Name of the dataset to list annotated datasets, - format: projects/{project_id}/datasets/{dataset_id} - filter (str): - Optional. Filter is not supported at this - moment. - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by - [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] - of the previous [DataLabelingService.ListAnnotatedDatasets] - call. Return first page if empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListAnnotatedDatasetsResponse(proto.Message): - r"""Results of listing annotated datasets for a dataset. - - Attributes: - annotated_datasets (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotatedDataset]): - The list of annotated datasets to return. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - annotated_datasets = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_dataset.AnnotatedDataset, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAnnotatedDatasetRequest(proto.Message): - r"""Request message for DeleteAnnotatedDataset. - - Attributes: - name (str): - Required. Name of the annotated dataset to delete, format: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class LabelImageRequest(proto.Message): - r"""Request message for starting an image labeling task. - - Attributes: - image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): - Configuration for image classification task. One of - image_classification_config, bounding_poly_config, - polyline_config and segmentation_config are required. - bounding_poly_config (google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig): - Configuration for bounding box and bounding poly task. One - of image_classification_config, bounding_poly_config, - polyline_config and segmentation_config are required. - polyline_config (google.cloud.datalabeling_v1beta1.types.PolylineConfig): - Configuration for polyline task. One of - image_classification_config, bounding_poly_config, - polyline_config and segmentation_config are required. - segmentation_config (google.cloud.datalabeling_v1beta1.types.SegmentationConfig): - Configuration for segmentation task. One of - image_classification_config, bounding_poly_config, - polyline_config and segmentation_config are required. - parent (str): - Required. Name of the dataset to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Required. Basic human annotation config. - feature (google.cloud.datalabeling_v1beta1.types.LabelImageRequest.Feature): - Required. The type of image labeling task. - """ - class Feature(proto.Enum): - r"""Image labeling task feature.""" - FEATURE_UNSPECIFIED = 0 - CLASSIFICATION = 1 - BOUNDING_BOX = 2 - ORIENTED_BOUNDING_BOX = 6 - BOUNDING_POLY = 3 - POLYLINE = 4 - SEGMENTATION = 5 - - image_classification_config = proto.Field( - proto.MESSAGE, - number=4, - oneof='request_config', - message=human_annotation_config.ImageClassificationConfig, - ) - bounding_poly_config = proto.Field( - proto.MESSAGE, - number=5, - oneof='request_config', - message=human_annotation_config.BoundingPolyConfig, - ) - polyline_config = proto.Field( - proto.MESSAGE, - number=6, - oneof='request_config', - message=human_annotation_config.PolylineConfig, - ) - segmentation_config = proto.Field( - proto.MESSAGE, - number=7, - oneof='request_config', - message=human_annotation_config.SegmentationConfig, - ) - parent = proto.Field( - proto.STRING, - number=1, - ) - basic_config = proto.Field( - proto.MESSAGE, - number=2, - message=human_annotation_config.HumanAnnotationConfig, - ) - feature = proto.Field( - proto.ENUM, - number=3, - enum=Feature, - ) - - -class LabelVideoRequest(proto.Message): - r"""Request message for LabelVideo. - - Attributes: - video_classification_config (google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig): - Configuration for video classification task. One of - video_classification_config, object_detection_config, - object_tracking_config and event_config is required. - object_detection_config (google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig): - Configuration for video object detection task. One of - video_classification_config, object_detection_config, - object_tracking_config and event_config is required. - object_tracking_config (google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig): - Configuration for video object tracking task. One of - video_classification_config, object_detection_config, - object_tracking_config and event_config is required. - event_config (google.cloud.datalabeling_v1beta1.types.EventConfig): - Configuration for video event task. One of - video_classification_config, object_detection_config, - object_tracking_config and event_config is required. - parent (str): - Required. Name of the dataset to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Required. Basic human annotation config. - feature (google.cloud.datalabeling_v1beta1.types.LabelVideoRequest.Feature): - Required. The type of video labeling task. - """ - class Feature(proto.Enum): - r"""Video labeling task feature.""" - FEATURE_UNSPECIFIED = 0 - CLASSIFICATION = 1 - OBJECT_DETECTION = 2 - OBJECT_TRACKING = 3 - EVENT = 4 - - video_classification_config = proto.Field( - proto.MESSAGE, - number=4, - oneof='request_config', - message=human_annotation_config.VideoClassificationConfig, - ) - object_detection_config = proto.Field( - proto.MESSAGE, - number=5, - oneof='request_config', - message=human_annotation_config.ObjectDetectionConfig, - ) - object_tracking_config = proto.Field( - proto.MESSAGE, - number=6, - oneof='request_config', - message=human_annotation_config.ObjectTrackingConfig, - ) - event_config = proto.Field( - proto.MESSAGE, - number=7, - oneof='request_config', - message=human_annotation_config.EventConfig, - ) - parent = proto.Field( - proto.STRING, - number=1, - ) - basic_config = proto.Field( - proto.MESSAGE, - number=2, - message=human_annotation_config.HumanAnnotationConfig, - ) - feature = proto.Field( - proto.ENUM, - number=3, - enum=Feature, - ) - - -class LabelTextRequest(proto.Message): - r"""Request message for LabelText. - - Attributes: - text_classification_config (google.cloud.datalabeling_v1beta1.types.TextClassificationConfig): - Configuration for text classification task. One of - text_classification_config and text_entity_extraction_config - is required. - text_entity_extraction_config (google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig): - Configuration for entity extraction task. One of - text_classification_config and text_entity_extraction_config - is required. - parent (str): - Required. Name of the data set to request labeling task, - format: projects/{project_id}/datasets/{dataset_id} - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Required. Basic human annotation config. - feature (google.cloud.datalabeling_v1beta1.types.LabelTextRequest.Feature): - Required. The type of text labeling task. - """ - class Feature(proto.Enum): - r"""Text labeling task feature.""" - FEATURE_UNSPECIFIED = 0 - TEXT_CLASSIFICATION = 1 - TEXT_ENTITY_EXTRACTION = 2 - - text_classification_config = proto.Field( - proto.MESSAGE, - number=4, - oneof='request_config', - message=human_annotation_config.TextClassificationConfig, - ) - text_entity_extraction_config = proto.Field( - proto.MESSAGE, - number=5, - oneof='request_config', - message=human_annotation_config.TextEntityExtractionConfig, - ) - parent = proto.Field( - proto.STRING, - number=1, - ) - basic_config = proto.Field( - proto.MESSAGE, - number=2, - message=human_annotation_config.HumanAnnotationConfig, - ) - feature = proto.Field( - proto.ENUM, - number=6, - enum=Feature, - ) - - -class GetExampleRequest(proto.Message): - r"""Request message for GetExample - - Attributes: - name (str): - Required. Name of example, format: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id}/examples/{example_id} - filter (str): - Optional. An expression for filtering Examples. Filter by - annotation_spec.display_name is supported. Format - "annotation_spec.display_name = {display_name}". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - - -class ListExamplesRequest(proto.Message): - r"""Request message for ListExamples. - - Attributes: - parent (str): - Required. Example resource parent. - filter (str): - Optional. An expression for filtering Examples. For - annotated datasets that have annotation spec set, filter by - annotation_spec.display_name is supported. Format - "annotation_spec.display_name = {display_name}". - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by - [ListExamplesResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListExamplesResponse.next_page_token] - of the previous [DataLabelingService.ListExamples] call. - Return first page if empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListExamplesResponse(proto.Message): - r"""Results of listing Examples in and annotated dataset. - - Attributes: - examples (Sequence[google.cloud.datalabeling_v1beta1.types.Example]): - The list of examples to return. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - examples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_dataset.Example, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateAnnotationSpecSetRequest(proto.Message): - r"""Request message for CreateAnnotationSpecSet. - - Attributes: - parent (str): - Required. AnnotationSpecSet resource parent, format: - projects/{project_id} - annotation_spec_set (google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet): - Required. Annotation spec set to create. Annotation specs - must be included. Only one annotation spec will be accepted - for annotation specs with same display_name. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - annotation_spec_set = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_annotation_spec_set.AnnotationSpecSet, - ) - - -class GetAnnotationSpecSetRequest(proto.Message): - r"""Request message for GetAnnotationSpecSet. - - Attributes: - name (str): - Required. AnnotationSpecSet resource name, format: - projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAnnotationSpecSetsRequest(proto.Message): - r"""Request message for ListAnnotationSpecSets. - - Attributes: - parent (str): - Required. Parent of AnnotationSpecSet resource, format: - projects/{project_id} - filter (str): - Optional. Filter is not supported at this - moment. - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by - [ListAnnotationSpecSetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotationSpecSetsResponse.next_page_token] - of the previous [DataLabelingService.ListAnnotationSpecSets] - call. Return first page if empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListAnnotationSpecSetsResponse(proto.Message): - r"""Results of listing annotation spec set under a project. - - Attributes: - annotation_spec_sets (Sequence[google.cloud.datalabeling_v1beta1.types.AnnotationSpecSet]): - The list of annotation spec sets. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - annotation_spec_sets = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_annotation_spec_set.AnnotationSpecSet, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAnnotationSpecSetRequest(proto.Message): - r"""Request message for DeleteAnnotationSpecSet. - - Attributes: - name (str): - Required. AnnotationSpec resource name, format: - ``projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateInstructionRequest(proto.Message): - r"""Request message for CreateInstruction. - - Attributes: - parent (str): - Required. Instruction resource parent, format: - projects/{project_id} - instruction (google.cloud.datalabeling_v1beta1.types.Instruction): - Required. Instruction of how to perform the - labeling task. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - instruction = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_instruction.Instruction, - ) - - -class GetInstructionRequest(proto.Message): - r"""Request message for GetInstruction. - - Attributes: - name (str): - Required. Instruction resource name, format: - projects/{project_id}/instructions/{instruction_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteInstructionRequest(proto.Message): - r"""Request message for DeleteInstruction. - - Attributes: - name (str): - Required. Instruction resource name, format: - projects/{project_id}/instructions/{instruction_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListInstructionsRequest(proto.Message): - r"""Request message for ListInstructions. - - Attributes: - parent (str): - Required. Instruction resource parent, format: - projects/{project_id} - filter (str): - Optional. Filter is not supported at this - moment. - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by - [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] - of the previous [DataLabelingService.ListInstructions] call. - Return first page if empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListInstructionsResponse(proto.Message): - r"""Results of listing instructions under a project. - - Attributes: - instructions (Sequence[google.cloud.datalabeling_v1beta1.types.Instruction]): - The list of Instructions to return. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - instructions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_instruction.Instruction, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEvaluationRequest(proto.Message): - r"""Request message for GetEvaluation. - - Attributes: - name (str): - Required. Name of the evaluation. Format: - - "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class SearchEvaluationsRequest(proto.Message): - r"""Request message for SearchEvaluation. - - Attributes: - parent (str): - Required. Evaluation search parent (project ID). Format: - "projects/{project_id}". - filter (str): - Optional. To search evaluations, you can filter by the - following: - - - evaluation\_job.evaluation_job_id (the last part of - [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) - - evaluation\_job.model_id (the {model_name} portion of - [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) - - evaluation\_job.evaluation_job_run_time_start (Minimum - threshold for the - [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] - that created the evaluation) - - evaluation\_job.evaluation_job_run_time_end (Maximum - threshold for the - [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] - that created the evaluation) - - evaluation\_job.job_state - ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) - - annotation\_spec.display_name (the Evaluation contains a - metric for the annotation spec with this - [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) - - To filter by multiple critiera, use the ``AND`` operator or - the ``OR`` operator. The following examples shows a string - that filters by several critiera: - - "evaluation\ *job.evaluation_job_id = {evaluation_job_id} - AND evaluation*\ job.model_id = {model_name} AND - evaluation\ *job.evaluation_job_run_time_start = - {timestamp_1} AND - evaluation*\ job.evaluation_job_run_time_end = {timestamp_2} - AND annotation\_spec.display_name = {display_name}". - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by the - [nextPageToken][google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.next_page_token] - of the response to a previous search request. - - If you don't specify this field, the API call requests the - first page of the search. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchEvaluationsResponse(proto.Message): - r"""Results of searching evaluations. - - Attributes: - evaluations (Sequence[google.cloud.datalabeling_v1beta1.types.Evaluation]): - The list of evaluations matching the search. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - evaluations = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=evaluation.Evaluation, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class SearchExampleComparisonsRequest(proto.Message): - r"""Request message of SearchExampleComparisons. - - Attributes: - parent (str): - Required. Name of the - [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] - resource to search for example comparisons from. Format: - - "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}". - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by the - [nextPageToken][SearchExampleComparisons.next_page_token] of - the response to a previous search rquest. - - If you don't specify this field, the API call requests the - first page of the search. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class SearchExampleComparisonsResponse(proto.Message): - r"""Results of searching example comparisons. - - Attributes: - example_comparisons (Sequence[google.cloud.datalabeling_v1beta1.types.SearchExampleComparisonsResponse.ExampleComparison]): - A list of example comparisons matching the - search criteria. - next_page_token (str): - A token to retrieve next page of results. - """ - - class ExampleComparison(proto.Message): - r"""Example comparisons comparing ground truth output and - predictions for a specific input. - - Attributes: - ground_truth_example (google.cloud.datalabeling_v1beta1.types.Example): - The ground truth output for the input. - model_created_examples (Sequence[google.cloud.datalabeling_v1beta1.types.Example]): - Predictions by the model for the input. - """ - - ground_truth_example = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_dataset.Example, - ) - model_created_examples = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gcd_dataset.Example, - ) - - @property - def raw_page(self): - return self - - example_comparisons = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ExampleComparison, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateEvaluationJobRequest(proto.Message): - r"""Request message for CreateEvaluationJob. - - Attributes: - parent (str): - Required. Evaluation job resource parent. Format: - "projects/{project_id}". - job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): - Required. The evaluation job to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - job = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_evaluation_job.EvaluationJob, - ) - - -class UpdateEvaluationJobRequest(proto.Message): - r"""Request message for UpdateEvaluationJob. - - Attributes: - evaluation_job (google.cloud.datalabeling_v1beta1.types.EvaluationJob): - Required. Evaluation job that is going to be - updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Mask for which fields to update. You can only - provide the following fields: - - - ``evaluationJobConfig.humanAnnotationConfig.instruction`` - - ``evaluationJobConfig.exampleCount`` - - ``evaluationJobConfig.exampleSamplePercentage`` - - You can provide more than one of these fields by separating - them with commas. - """ - - evaluation_job = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_evaluation_job.EvaluationJob, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetEvaluationJobRequest(proto.Message): - r"""Request message for GetEvaluationJob. - - Attributes: - name (str): - Required. Name of the evaluation job. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class PauseEvaluationJobRequest(proto.Message): - r"""Request message for PauseEvaluationJob. - - Attributes: - name (str): - Required. Name of the evaluation job that is going to be - paused. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ResumeEvaluationJobRequest(proto.Message): - r"""Request message ResumeEvaluationJob. - - Attributes: - name (str): - Required. Name of the evaluation job that is going to be - resumed. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteEvaluationJobRequest(proto.Message): - r"""Request message DeleteEvaluationJob. - - Attributes: - name (str): - Required. Name of the evaluation job that is going to be - deleted. Format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEvaluationJobsRequest(proto.Message): - r"""Request message for ListEvaluationJobs. - - Attributes: - parent (str): - Required. Evaluation job resource parent. Format: - "projects/{project_id}". - filter (str): - Optional. You can filter the jobs to list by model_id (also - known as model_name, as described in - [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) - or by evaluation job state (as described in - [EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]). - To filter by both criteria, use the ``AND`` operator or the - ``OR`` operator. For example, you can use the following - string for your filter: "evaluation\ *job.model_id = - {model_name} AND evaluation*\ job.state = - {evaluation_job_state}". - page_size (int): - Optional. Requested page size. Server may - return fewer results than requested. Default - value is 100. - page_token (str): - Optional. A token identifying a page of results for the - server to return. Typically obtained by the - [nextPageToken][google.cloud.datalabeling.v1beta1.ListEvaluationJobsResponse.next_page_token] - in the response to the previous request. The request returns - the first page if this is empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListEvaluationJobsResponse(proto.Message): - r"""Results for listing evaluation jobs. - - Attributes: - evaluation_jobs (Sequence[google.cloud.datalabeling_v1beta1.types.EvaluationJob]): - The list of evaluation jobs to return. - next_page_token (str): - A token to retrieve next page of results. - """ - - @property - def raw_page(self): - return self - - evaluation_jobs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_evaluation_job.EvaluationJob, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py deleted file mode 100644 index bba9a8c..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/data_payloads.py +++ /dev/null @@ -1,142 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'ImagePayload', - 'TextPayload', - 'VideoThumbnail', - 'VideoPayload', - }, -) - - -class ImagePayload(proto.Message): - r"""Container of information about an image. - - Attributes: - mime_type (str): - Image format. - image_thumbnail (bytes): - A byte string of a thumbnail image. - image_uri (str): - Image uri from the user bucket. - signed_uri (str): - Signed uri of the image file in the service - bucket. - """ - - mime_type = proto.Field( - proto.STRING, - number=1, - ) - image_thumbnail = proto.Field( - proto.BYTES, - number=2, - ) - image_uri = proto.Field( - proto.STRING, - number=3, - ) - signed_uri = proto.Field( - proto.STRING, - number=4, - ) - - -class TextPayload(proto.Message): - r"""Container of information about a piece of text. - - Attributes: - text_content (str): - Text content. - """ - - text_content = proto.Field( - proto.STRING, - number=1, - ) - - -class VideoThumbnail(proto.Message): - r"""Container of information of a video thumbnail. - - Attributes: - thumbnail (bytes): - A byte string of the video frame. - time_offset (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the - video, corresponding to the video frame where - the thumbnail has been extracted from. - """ - - thumbnail = proto.Field( - proto.BYTES, - number=1, - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class VideoPayload(proto.Message): - r"""Container of information of a video. - - Attributes: - mime_type (str): - Video format. - video_uri (str): - Video uri from the user bucket. - video_thumbnails (Sequence[google.cloud.datalabeling_v1beta1.types.VideoThumbnail]): - The list of video thumbnails. - frame_rate (float): - FPS of the video. - signed_uri (str): - Signed uri of the video file in the service - bucket. - """ - - mime_type = proto.Field( - proto.STRING, - number=1, - ) - video_uri = proto.Field( - proto.STRING, - number=2, - ) - video_thumbnails = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='VideoThumbnail', - ) - frame_rate = proto.Field( - proto.FLOAT, - number=4, - ) - signed_uri = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py deleted file mode 100644 index b7099d4..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/dataset.py +++ /dev/null @@ -1,645 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.datalabeling_v1beta1.types import annotation -from google.cloud.datalabeling_v1beta1.types import data_payloads -from google.cloud.datalabeling_v1beta1.types import human_annotation_config as gcd_human_annotation_config -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'DataType', - 'Dataset', - 'InputConfig', - 'TextMetadata', - 'ClassificationMetadata', - 'GcsSource', - 'BigQuerySource', - 'OutputConfig', - 'GcsDestination', - 'GcsFolderDestination', - 'DataItem', - 'AnnotatedDataset', - 'LabelStats', - 'AnnotatedDatasetMetadata', - 'Example', - }, -) - - -class DataType(proto.Enum): - r"""""" - DATA_TYPE_UNSPECIFIED = 0 - IMAGE = 1 - VIDEO = 2 - TEXT = 4 - GENERAL_DATA = 6 - - -class Dataset(proto.Message): - r"""Dataset is the resource to hold your data. You can request - multiple labeling tasks for a dataset while each one will - generate an AnnotatedDataset. - - Attributes: - name (str): - Output only. Dataset resource name, format is: - projects/{project_id}/datasets/{dataset_id} - display_name (str): - Required. The display name of the dataset. - Maximum of 64 characters. - description (str): - Optional. User-provided description of the - annotation specification set. The description - can be up to 10000 characters long. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time the dataset is created. - input_configs (Sequence[google.cloud.datalabeling_v1beta1.types.InputConfig]): - Output only. This is populated with the - original input configs where ImportData is - called. It is available only after the clients - import data to this dataset. - blocking_resources (Sequence[str]): - Output only. The names of any related - resources that are blocking changes to the - dataset. - data_item_count (int): - Output only. The number of data items in the - dataset. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - input_configs = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='InputConfig', - ) - blocking_resources = proto.RepeatedField( - proto.STRING, - number=6, - ) - data_item_count = proto.Field( - proto.INT64, - number=7, - ) - - -class InputConfig(proto.Message): - r"""The configuration of input data, including data type, - location, etc. - - Attributes: - text_metadata (google.cloud.datalabeling_v1beta1.types.TextMetadata): - Required for text import, as language code - must be specified. - gcs_source (google.cloud.datalabeling_v1beta1.types.GcsSource): - Source located in Cloud Storage. - bigquery_source (google.cloud.datalabeling_v1beta1.types.BigQuerySource): - Source located in BigQuery. You must specify this field if - you are using this InputConfig in an - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob]. - data_type (google.cloud.datalabeling_v1beta1.types.DataType): - Required. Data type must be specifed when - user tries to import data. - annotation_type (google.cloud.datalabeling_v1beta1.types.AnnotationType): - Optional. The type of annotation to be performed on this - data. You must specify this field if you are using this - InputConfig in an - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob]. - classification_metadata (google.cloud.datalabeling_v1beta1.types.ClassificationMetadata): - Optional. Metadata about annotations for the input. You must - specify this field if you are using this InputConfig in an - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] - for a model version that performs classification. - """ - - text_metadata = proto.Field( - proto.MESSAGE, - number=6, - oneof='data_type_metadata', - message='TextMetadata', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - bigquery_source = proto.Field( - proto.MESSAGE, - number=5, - oneof='source', - message='BigQuerySource', - ) - data_type = proto.Field( - proto.ENUM, - number=1, - enum='DataType', - ) - annotation_type = proto.Field( - proto.ENUM, - number=3, - enum=annotation.AnnotationType, - ) - classification_metadata = proto.Field( - proto.MESSAGE, - number=4, - message='ClassificationMetadata', - ) - - -class TextMetadata(proto.Message): - r"""Metadata for the text. - - Attributes: - language_code (str): - The language of this text, as a - `BCP-47 `__. - Default value is en-US. - """ - - language_code = proto.Field( - proto.STRING, - number=1, - ) - - -class ClassificationMetadata(proto.Message): - r"""Metadata for classification annotations. - - Attributes: - is_multi_label (bool): - Whether the classification task is multi- - abel or not. - """ - - is_multi_label = proto.Field( - proto.BOOL, - number=1, - ) - - -class GcsSource(proto.Message): - r"""Source of the Cloud Storage file to be imported. - - Attributes: - input_uri (str): - Required. The input URI of source file. This must be a Cloud - Storage path (``gs://...``). - mime_type (str): - Required. The format of the source file. Only - "text/csv" is supported. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - mime_type = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""The BigQuery location for input data. If used in an - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob], - this is where the service saves the prediction input and output - sampled from the model version. - - Attributes: - input_uri (str): - Required. BigQuery URI to a table, up to 2,000 characters - long. If you specify the URI of a table that does not exist, - Data Labeling Service creates a table at the URI with the - correct schema when you create your - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob]. - If you specify the URI of a table that already exists, it - must have the `correct - schema `__. - - Provide the table URI in the following format: - - "bq://{your_project_id}/{your_dataset_name}/{your_table_name}" - - `Learn - more `__. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - - -class OutputConfig(proto.Message): - r"""The configuration of output data. - - Attributes: - gcs_destination (google.cloud.datalabeling_v1beta1.types.GcsDestination): - Output to a file in Cloud Storage. Should be - used for labeling output other than image - segmentation. - gcs_folder_destination (google.cloud.datalabeling_v1beta1.types.GcsFolderDestination): - Output to a folder in Cloud Storage. Should - be used for image segmentation labeling output. - """ - - gcs_destination = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - gcs_folder_destination = proto.Field( - proto.MESSAGE, - number=2, - oneof='destination', - message='GcsFolderDestination', - ) - - -class GcsDestination(proto.Message): - r"""Export destination of the data.Only gcs path is allowed in - output_uri. - - Attributes: - output_uri (str): - Required. The output uri of destination file. - mime_type (str): - Required. The format of the gcs destination. - Only "text/csv" and "application/json" - are supported. - """ - - output_uri = proto.Field( - proto.STRING, - number=1, - ) - mime_type = proto.Field( - proto.STRING, - number=2, - ) - - -class GcsFolderDestination(proto.Message): - r"""Export folder destination of the data. - - Attributes: - output_folder_uri (str): - Required. Cloud Storage directory to export - data to. - """ - - output_folder_uri = proto.Field( - proto.STRING, - number=1, - ) - - -class DataItem(proto.Message): - r"""DataItem is a piece of data, without annotation. For example, - an image. - - Attributes: - image_payload (google.cloud.datalabeling_v1beta1.types.ImagePayload): - The image payload, a container of the image - bytes/uri. - text_payload (google.cloud.datalabeling_v1beta1.types.TextPayload): - The text payload, a container of text - content. - video_payload (google.cloud.datalabeling_v1beta1.types.VideoPayload): - The video payload, a container of the video - uri. - name (str): - Output only. Name of the data item, in format of: - projects/{project_id}/datasets/{dataset_id}/dataItems/{data_item_id} - """ - - image_payload = proto.Field( - proto.MESSAGE, - number=2, - oneof='payload', - message=data_payloads.ImagePayload, - ) - text_payload = proto.Field( - proto.MESSAGE, - number=3, - oneof='payload', - message=data_payloads.TextPayload, - ) - video_payload = proto.Field( - proto.MESSAGE, - number=4, - oneof='payload', - message=data_payloads.VideoPayload, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - - -class AnnotatedDataset(proto.Message): - r"""AnnotatedDataset is a set holding annotations for data in a - Dataset. Each labeling task will generate an AnnotatedDataset - under the Dataset that the task is requested for. - - Attributes: - name (str): - Output only. AnnotatedDataset resource name in format of: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id} - display_name (str): - Output only. The display name of the - AnnotatedDataset. It is specified in - HumanAnnotationConfig when user starts a - labeling task. Maximum of 64 characters. - description (str): - Output only. The description of the - AnnotatedDataset. It is specified in - HumanAnnotationConfig when user starts a - labeling task. Maximum of 10000 characters. - annotation_source (google.cloud.datalabeling_v1beta1.types.AnnotationSource): - Output only. Source of the annotation. - annotation_type (google.cloud.datalabeling_v1beta1.types.AnnotationType): - Output only. Type of the annotation. It is - specified when starting labeling task. - example_count (int): - Output only. Number of examples in the - annotated dataset. - completed_example_count (int): - Output only. Number of examples that have - annotation in the annotated dataset. - label_stats (google.cloud.datalabeling_v1beta1.types.LabelStats): - Output only. Per label statistics. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time the AnnotatedDataset was - created. - metadata (google.cloud.datalabeling_v1beta1.types.AnnotatedDatasetMetadata): - Output only. Additional information about - AnnotatedDataset. - blocking_resources (Sequence[str]): - Output only. The names of any related - resources that are blocking changes to the - annotated dataset. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=9, - ) - annotation_source = proto.Field( - proto.ENUM, - number=3, - enum=annotation.AnnotationSource, - ) - annotation_type = proto.Field( - proto.ENUM, - number=8, - enum=annotation.AnnotationType, - ) - example_count = proto.Field( - proto.INT64, - number=4, - ) - completed_example_count = proto.Field( - proto.INT64, - number=5, - ) - label_stats = proto.Field( - proto.MESSAGE, - number=6, - message='LabelStats', - ) - create_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - metadata = proto.Field( - proto.MESSAGE, - number=10, - message='AnnotatedDatasetMetadata', - ) - blocking_resources = proto.RepeatedField( - proto.STRING, - number=11, - ) - - -class LabelStats(proto.Message): - r"""Statistics about annotation specs. - - Attributes: - example_count (Sequence[google.cloud.datalabeling_v1beta1.types.LabelStats.ExampleCountEntry]): - Map of each annotation spec's example count. - Key is the annotation spec name and value is the - number of examples for that annotation spec. If - the annotated dataset does not have annotation - spec, the map will return a pair where the key - is empty string and value is the total number of - annotations. - """ - - example_count = proto.MapField( - proto.STRING, - proto.INT64, - number=1, - ) - - -class AnnotatedDatasetMetadata(proto.Message): - r"""Metadata on AnnotatedDataset. - - Attributes: - image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): - Configuration for image classification task. - bounding_poly_config (google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig): - Configuration for image bounding box and - bounding poly task. - polyline_config (google.cloud.datalabeling_v1beta1.types.PolylineConfig): - Configuration for image polyline task. - segmentation_config (google.cloud.datalabeling_v1beta1.types.SegmentationConfig): - Configuration for image segmentation task. - video_classification_config (google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig): - Configuration for video classification task. - object_detection_config (google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig): - Configuration for video object detection - task. - object_tracking_config (google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig): - Configuration for video object tracking task. - event_config (google.cloud.datalabeling_v1beta1.types.EventConfig): - Configuration for video event labeling task. - text_classification_config (google.cloud.datalabeling_v1beta1.types.TextClassificationConfig): - Configuration for text classification task. - text_entity_extraction_config (google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig): - Configuration for text entity extraction - task. - human_annotation_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - HumanAnnotationConfig used when requesting - the human labeling task for this - AnnotatedDataset. - """ - - image_classification_config = proto.Field( - proto.MESSAGE, - number=2, - oneof='annotation_request_config', - message=gcd_human_annotation_config.ImageClassificationConfig, - ) - bounding_poly_config = proto.Field( - proto.MESSAGE, - number=3, - oneof='annotation_request_config', - message=gcd_human_annotation_config.BoundingPolyConfig, - ) - polyline_config = proto.Field( - proto.MESSAGE, - number=4, - oneof='annotation_request_config', - message=gcd_human_annotation_config.PolylineConfig, - ) - segmentation_config = proto.Field( - proto.MESSAGE, - number=5, - oneof='annotation_request_config', - message=gcd_human_annotation_config.SegmentationConfig, - ) - video_classification_config = proto.Field( - proto.MESSAGE, - number=6, - oneof='annotation_request_config', - message=gcd_human_annotation_config.VideoClassificationConfig, - ) - object_detection_config = proto.Field( - proto.MESSAGE, - number=7, - oneof='annotation_request_config', - message=gcd_human_annotation_config.ObjectDetectionConfig, - ) - object_tracking_config = proto.Field( - proto.MESSAGE, - number=8, - oneof='annotation_request_config', - message=gcd_human_annotation_config.ObjectTrackingConfig, - ) - event_config = proto.Field( - proto.MESSAGE, - number=9, - oneof='annotation_request_config', - message=gcd_human_annotation_config.EventConfig, - ) - text_classification_config = proto.Field( - proto.MESSAGE, - number=10, - oneof='annotation_request_config', - message=gcd_human_annotation_config.TextClassificationConfig, - ) - text_entity_extraction_config = proto.Field( - proto.MESSAGE, - number=11, - oneof='annotation_request_config', - message=gcd_human_annotation_config.TextEntityExtractionConfig, - ) - human_annotation_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_human_annotation_config.HumanAnnotationConfig, - ) - - -class Example(proto.Message): - r"""An Example is a piece of data and its annotation. For - example, an image with label "house". - - Attributes: - image_payload (google.cloud.datalabeling_v1beta1.types.ImagePayload): - The image payload, a container of the image - bytes/uri. - text_payload (google.cloud.datalabeling_v1beta1.types.TextPayload): - The text payload, a container of the text - content. - video_payload (google.cloud.datalabeling_v1beta1.types.VideoPayload): - The video payload, a container of the video - uri. - name (str): - Output only. Name of the example, in format of: - projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/ - {annotated_dataset_id}/examples/{example_id} - annotations (Sequence[google.cloud.datalabeling_v1beta1.types.Annotation]): - Output only. Annotations for the piece of - data in Example. One piece of data can have - multiple annotations. - """ - - image_payload = proto.Field( - proto.MESSAGE, - number=2, - oneof='payload', - message=data_payloads.ImagePayload, - ) - text_payload = proto.Field( - proto.MESSAGE, - number=6, - oneof='payload', - message=data_payloads.TextPayload, - ) - video_payload = proto.Field( - proto.MESSAGE, - number=7, - oneof='payload', - message=data_payloads.VideoPayload, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - annotations = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=annotation.Annotation, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py deleted file mode 100644 index c34524a..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation.py +++ /dev/null @@ -1,405 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.datalabeling_v1beta1.types import annotation -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'Evaluation', - 'EvaluationConfig', - 'BoundingBoxEvaluationOptions', - 'EvaluationMetrics', - 'ClassificationMetrics', - 'ObjectDetectionMetrics', - 'PrCurve', - 'ConfusionMatrix', - }, -) - - -class Evaluation(proto.Message): - r"""Describes an evaluation between a machine learning model's - predictions and ground truth labels. Created when an - [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] - runs successfully. - - Attributes: - name (str): - Output only. Resource name of an evaluation. The name has - the following format: - - "projects/{project_id}/datasets/{dataset_id}/evaluations/{evaluation_id}' - config (google.cloud.datalabeling_v1beta1.types.EvaluationConfig): - Output only. Options used in the evaluation - job that created this evaluation. - evaluation_job_run_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp for when the - evaluation job that created this evaluation ran. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp for when this - evaluation was created. - evaluation_metrics (google.cloud.datalabeling_v1beta1.types.EvaluationMetrics): - Output only. Metrics comparing predictions to - ground truth labels. - annotation_type (google.cloud.datalabeling_v1beta1.types.AnnotationType): - Output only. Type of task that the model version being - evaluated performs, as defined in the - - [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config] - field of the evaluation job that created this evaluation. - evaluated_item_count (int): - Output only. The number of items in the - ground truth dataset that were used for this - evaluation. Only populated when the evaulation - is for certain AnnotationTypes. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - config = proto.Field( - proto.MESSAGE, - number=2, - message='EvaluationConfig', - ) - evaluation_job_run_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - evaluation_metrics = proto.Field( - proto.MESSAGE, - number=5, - message='EvaluationMetrics', - ) - annotation_type = proto.Field( - proto.ENUM, - number=6, - enum=annotation.AnnotationType, - ) - evaluated_item_count = proto.Field( - proto.INT64, - number=7, - ) - - -class EvaluationConfig(proto.Message): - r"""Configuration details used for calculating evaluation metrics and - creating an - [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation]. - - Attributes: - bounding_box_evaluation_options (google.cloud.datalabeling_v1beta1.types.BoundingBoxEvaluationOptions): - Only specify this field if the related model performs image - object detection (``IMAGE_BOUNDING_BOX_ANNOTATION``). - Describes how to evaluate bounding boxes. - """ - - bounding_box_evaluation_options = proto.Field( - proto.MESSAGE, - number=1, - oneof='vertical_option', - message='BoundingBoxEvaluationOptions', - ) - - -class BoundingBoxEvaluationOptions(proto.Message): - r"""Options regarding evaluation between bounding boxes. - - Attributes: - iou_threshold (float): - Minimum [intersection-over-union - - (IOU)](/vision/automl/object-detection/docs/evaluate#intersection-over-union) - required for 2 bounding boxes to be considered a match. This - must be a number between 0 and 1. - """ - - iou_threshold = proto.Field( - proto.FLOAT, - number=1, - ) - - -class EvaluationMetrics(proto.Message): - r""" - - Attributes: - classification_metrics (google.cloud.datalabeling_v1beta1.types.ClassificationMetrics): - - object_detection_metrics (google.cloud.datalabeling_v1beta1.types.ObjectDetectionMetrics): - - """ - - classification_metrics = proto.Field( - proto.MESSAGE, - number=1, - oneof='metrics', - message='ClassificationMetrics', - ) - object_detection_metrics = proto.Field( - proto.MESSAGE, - number=2, - oneof='metrics', - message='ObjectDetectionMetrics', - ) - - -class ClassificationMetrics(proto.Message): - r"""Metrics calculated for a classification model. - - Attributes: - pr_curve (google.cloud.datalabeling_v1beta1.types.PrCurve): - Precision-recall curve based on ground truth - labels, predicted labels, and scores for the - predicted labels. - confusion_matrix (google.cloud.datalabeling_v1beta1.types.ConfusionMatrix): - Confusion matrix of predicted labels vs. - ground truth labels. - """ - - pr_curve = proto.Field( - proto.MESSAGE, - number=1, - message='PrCurve', - ) - confusion_matrix = proto.Field( - proto.MESSAGE, - number=2, - message='ConfusionMatrix', - ) - - -class ObjectDetectionMetrics(proto.Message): - r"""Metrics calculated for an image object detection (bounding - box) model. - - Attributes: - pr_curve (google.cloud.datalabeling_v1beta1.types.PrCurve): - Precision-recall curve. - """ - - pr_curve = proto.Field( - proto.MESSAGE, - number=1, - message='PrCurve', - ) - - -class PrCurve(proto.Message): - r""" - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - The annotation spec of the label for which - the precision-recall curve calculated. If this - field is empty, that means the precision-recall - curve is an aggregate curve for all labels. - area_under_curve (float): - Area under the precision-recall curve. Not to - be confused with area under a receiver operating - characteristic (ROC) curve. - confidence_metrics_entries (Sequence[google.cloud.datalabeling_v1beta1.types.PrCurve.ConfidenceMetricsEntry]): - Entries that make up the precision-recall graph. Each entry - is a "point" on the graph drawn for a different - ``confidence_threshold``. - mean_average_precision (float): - Mean average prcision of this curve. - """ - - class ConfidenceMetricsEntry(proto.Message): - r""" - - Attributes: - confidence_threshold (float): - Threshold used for this entry. - - For classification tasks, this is a classification - threshold: a predicted label is categorized as positive or - negative (in the context of this point on the PR curve) - based on whether the label's score meets this threshold. - - For image object detection (bounding box) tasks, this is the - [intersection-over-union - - (IOU)](/vision/automl/object-detection/docs/evaluate#intersection-over-union) - threshold for the context of this point on the PR curve. - recall (float): - Recall value. - precision (float): - Precision value. - f1_score (float): - Harmonic mean of recall and precision. - recall_at1 (float): - Recall value for entries with label that has - highest score. - precision_at1 (float): - Precision value for entries with label that - has highest score. - f1_score_at1 (float): - The harmonic mean of - [recall_at1][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.recall_at1] - and - [precision_at1][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.precision_at1]. - recall_at5 (float): - Recall value for entries with label that has - highest 5 scores. - precision_at5 (float): - Precision value for entries with label that - has highest 5 scores. - f1_score_at5 (float): - The harmonic mean of - [recall_at5][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.recall_at5] - and - [precision_at5][google.cloud.datalabeling.v1beta1.PrCurve.ConfidenceMetricsEntry.precision_at5]. - """ - - confidence_threshold = proto.Field( - proto.FLOAT, - number=1, - ) - recall = proto.Field( - proto.FLOAT, - number=2, - ) - precision = proto.Field( - proto.FLOAT, - number=3, - ) - f1_score = proto.Field( - proto.FLOAT, - number=4, - ) - recall_at1 = proto.Field( - proto.FLOAT, - number=5, - ) - precision_at1 = proto.Field( - proto.FLOAT, - number=6, - ) - f1_score_at1 = proto.Field( - proto.FLOAT, - number=7, - ) - recall_at5 = proto.Field( - proto.FLOAT, - number=8, - ) - precision_at5 = proto.Field( - proto.FLOAT, - number=9, - ) - f1_score_at5 = proto.Field( - proto.FLOAT, - number=10, - ) - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - area_under_curve = proto.Field( - proto.FLOAT, - number=2, - ) - confidence_metrics_entries = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ConfidenceMetricsEntry, - ) - mean_average_precision = proto.Field( - proto.FLOAT, - number=4, - ) - - -class ConfusionMatrix(proto.Message): - r"""Confusion matrix of the model running the classification. - Only applicable when the metrics entry aggregates multiple - labels. Not applicable when the entry is for a single label. - - Attributes: - row (Sequence[google.cloud.datalabeling_v1beta1.types.ConfusionMatrix.Row]): - - """ - - class ConfusionMatrixEntry(proto.Message): - r""" - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - The annotation spec of a predicted label. - item_count (int): - Number of items predicted to have this label. (The ground - truth label for these items is the ``Row.annotationSpec`` of - this entry's parent.) - """ - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - item_count = proto.Field( - proto.INT32, - number=2, - ) - - class Row(proto.Message): - r"""A row in the confusion matrix. Each entry in this row has the - same ground truth label. - - Attributes: - annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec): - The annotation spec of the ground truth label - for this row. - entries (Sequence[google.cloud.datalabeling_v1beta1.types.ConfusionMatrix.ConfusionMatrixEntry]): - A list of the confusion matrix entries. One - entry for each possible predicted label. - """ - - annotation_spec = proto.Field( - proto.MESSAGE, - number=1, - message=annotation_spec_set.AnnotationSpec, - ) - entries = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ConfusionMatrix.ConfusionMatrixEntry', - ) - - row = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Row, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py deleted file mode 100644 index 88c9624..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/evaluation_job.py +++ /dev/null @@ -1,375 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import human_annotation_config as gcd_human_annotation_config -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'EvaluationJob', - 'EvaluationJobConfig', - 'EvaluationJobAlertConfig', - 'Attempt', - }, -) - - -class EvaluationJob(proto.Message): - r"""Defines an evaluation job that runs periodically to generate - [Evaluations][google.cloud.datalabeling.v1beta1.Evaluation]. - `Creating an evaluation - job `__ is the - starting point for using continuous evaluation. - - Attributes: - name (str): - Output only. After you create a job, Data Labeling Service - assigns a name to the job with the following format: - - "projects/{project_id}/evaluationJobs/{evaluation_job_id}". - description (str): - Required. Description of the job. The - description can be up to 25,000 characters long. - state (google.cloud.datalabeling_v1beta1.types.EvaluationJob.State): - Output only. Describes the current state of - the job. - schedule (str): - Required. Describes the interval at which the job runs. This - interval must be at least 1 day, and it is rounded to the - nearest day. For example, if you specify a 50-hour interval, - the job runs every 2 days. - - You can provide the schedule in `crontab - format `__ - or in an `English-like - format `__. - - Regardless of what you specify, the job will run at 10:00 AM - UTC. Only the interval from this schedule is used, not the - specific time of day. - model_version (str): - Required. The `AI Platform Prediction model - version `__ to be - evaluated. Prediction input and output is sampled from this - model version. When creating an evaluation job, specify the - model version in the following format: - - "projects/{project_id}/models/{model_name}/versions/{version_name}" - - There can only be one evaluation job per model version. - evaluation_job_config (google.cloud.datalabeling_v1beta1.types.EvaluationJobConfig): - Required. Configuration details for the - evaluation job. - annotation_spec_set (str): - Required. Name of the - [AnnotationSpecSet][google.cloud.datalabeling.v1beta1.AnnotationSpecSet] - describing all the labels that your machine learning model - outputs. You must create this resource before you create an - evaluation job and provide its name in the following format: - - "projects/{project_id}/annotationSpecSets/{annotation_spec_set_id}". - label_missing_ground_truth (bool): - Required. Whether you want Data Labeling Service to provide - ground truth labels for prediction input. If you want the - service to assign human labelers to annotate your data, set - this to ``true``. If you want to provide your own ground - truth labels in the evaluation job's BigQuery table, set - this to ``false``. - attempts (Sequence[google.cloud.datalabeling_v1beta1.types.Attempt]): - Output only. Every time the evaluation job - runs and an error occurs, the failed attempt is - appended to this array. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp of when this - evaluation job was created. - """ - class State(proto.Enum): - r"""State of the job.""" - STATE_UNSPECIFIED = 0 - SCHEDULED = 1 - RUNNING = 2 - PAUSED = 3 - STOPPED = 4 - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - state = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - schedule = proto.Field( - proto.STRING, - number=4, - ) - model_version = proto.Field( - proto.STRING, - number=5, - ) - evaluation_job_config = proto.Field( - proto.MESSAGE, - number=6, - message='EvaluationJobConfig', - ) - annotation_spec_set = proto.Field( - proto.STRING, - number=7, - ) - label_missing_ground_truth = proto.Field( - proto.BOOL, - number=8, - ) - attempts = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Attempt', - ) - create_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -class EvaluationJobConfig(proto.Message): - r"""Configures specific details of how a continuous evaluation - job works. Provide this configuration when you create an - EvaluationJob. - - Attributes: - image_classification_config (google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig): - Specify this field if your model version performs image - classification or general classification. - - ``annotationSpecSet`` in this configuration must match - [EvaluationJob.annotationSpecSet][google.cloud.datalabeling.v1beta1.EvaluationJob.annotation_spec_set]. - ``allowMultiLabel`` in this configuration must match - ``classificationMetadata.isMultiLabel`` in - [input_config][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]. - bounding_poly_config (google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig): - Specify this field if your model version performs image - object detection (bounding box detection). - - ``annotationSpecSet`` in this configuration must match - [EvaluationJob.annotationSpecSet][google.cloud.datalabeling.v1beta1.EvaluationJob.annotation_spec_set]. - text_classification_config (google.cloud.datalabeling_v1beta1.types.TextClassificationConfig): - Specify this field if your model version performs text - classification. - - ``annotationSpecSet`` in this configuration must match - [EvaluationJob.annotationSpecSet][google.cloud.datalabeling.v1beta1.EvaluationJob.annotation_spec_set]. - ``allowMultiLabel`` in this configuration must match - ``classificationMetadata.isMultiLabel`` in - [input_config][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]. - input_config (google.cloud.datalabeling_v1beta1.types.InputConfig): - Rquired. Details for the sampled prediction input. Within - this configuration, there are requirements for several - fields: - - - ``dataType`` must be one of ``IMAGE``, ``TEXT``, or - ``GENERAL_DATA``. - - ``annotationType`` must be one of - ``IMAGE_CLASSIFICATION_ANNOTATION``, - ``TEXT_CLASSIFICATION_ANNOTATION``, - ``GENERAL_CLASSIFICATION_ANNOTATION``, or - ``IMAGE_BOUNDING_BOX_ANNOTATION`` (image object - detection). - - If your machine learning model performs classification, - you must specify ``classificationMetadata.isMultiLabel``. - - You must specify ``bigquerySource`` (not ``gcsSource``). - evaluation_config (google.cloud.datalabeling_v1beta1.types.EvaluationConfig): - Required. Details for calculating evaluation metrics and - creating - [Evaulations][google.cloud.datalabeling.v1beta1.Evaluation]. - If your model version performs image object detection, you - must specify the ``boundingBoxEvaluationOptions`` field - within this configuration. Otherwise, provide an empty - object for this configuration. - human_annotation_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Optional. Details for human annotation of your data. If you - set - [labelMissingGroundTruth][google.cloud.datalabeling.v1beta1.EvaluationJob.label_missing_ground_truth] - to ``true`` for this evaluation job, then you must specify - this field. If you plan to provide your own ground truth - labels, then omit this field. - - Note that you must create an - [Instruction][google.cloud.datalabeling.v1beta1.Instruction] - resource before you can specify this field. Provide the name - of the instruction resource in the ``instruction`` field - within this configuration. - bigquery_import_keys (Sequence[google.cloud.datalabeling_v1beta1.types.EvaluationJobConfig.BigqueryImportKeysEntry]): - Required. Prediction keys that tell Data Labeling Service - where to find the data for evaluation in your BigQuery - table. When the service samples prediction input and output - from your model version and saves it to BigQuery, the data - gets stored as JSON strings in the BigQuery table. These - keys tell Data Labeling Service how to parse the JSON. - - You can provide the following entries in this field: - - - ``data_json_key``: the data key for prediction input. You - must provide either this key or ``reference_json_key``. - - ``reference_json_key``: the data reference key for - prediction input. You must provide either this key or - ``data_json_key``. - - ``label_json_key``: the label key for prediction output. - Required. - - ``label_score_json_key``: the score key for prediction - output. Required. - - ``bounding_box_json_key``: the bounding box key for - prediction output. Required if your model version perform - image object detection. - - Learn `how to configure prediction - keys `__. - example_count (int): - Required. The maximum number of predictions to sample and - save to BigQuery during each [evaluation - interval][google.cloud.datalabeling.v1beta1.EvaluationJob.schedule]. - This limit overrides ``example_sample_percentage``: even if - the service has not sampled enough predictions to fulfill - ``example_sample_perecentage`` during an interval, it stops - sampling predictions when it meets this limit. - example_sample_percentage (float): - Required. Fraction of predictions to sample and save to - BigQuery during each [evaluation - interval][google.cloud.datalabeling.v1beta1.EvaluationJob.schedule]. - For example, 0.1 means 10% of predictions served by your - model version get saved to BigQuery. - evaluation_job_alert_config (google.cloud.datalabeling_v1beta1.types.EvaluationJobAlertConfig): - Optional. Configuration details for - evaluation job alerts. Specify this field if you - want to receive email alerts if the evaluation - job finds that your predictions have low mean - average precision during a run. - """ - - image_classification_config = proto.Field( - proto.MESSAGE, - number=4, - oneof='human_annotation_request_config', - message=gcd_human_annotation_config.ImageClassificationConfig, - ) - bounding_poly_config = proto.Field( - proto.MESSAGE, - number=5, - oneof='human_annotation_request_config', - message=gcd_human_annotation_config.BoundingPolyConfig, - ) - text_classification_config = proto.Field( - proto.MESSAGE, - number=8, - oneof='human_annotation_request_config', - message=gcd_human_annotation_config.TextClassificationConfig, - ) - input_config = proto.Field( - proto.MESSAGE, - number=1, - message=dataset.InputConfig, - ) - evaluation_config = proto.Field( - proto.MESSAGE, - number=2, - message=evaluation.EvaluationConfig, - ) - human_annotation_config = proto.Field( - proto.MESSAGE, - number=3, - message=gcd_human_annotation_config.HumanAnnotationConfig, - ) - bigquery_import_keys = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - example_count = proto.Field( - proto.INT32, - number=10, - ) - example_sample_percentage = proto.Field( - proto.DOUBLE, - number=11, - ) - evaluation_job_alert_config = proto.Field( - proto.MESSAGE, - number=13, - message='EvaluationJobAlertConfig', - ) - - -class EvaluationJobAlertConfig(proto.Message): - r"""Provides details for how an evaluation job sends email alerts - based on the results of a run. - - Attributes: - email (str): - Required. An email address to send alerts to. - min_acceptable_mean_average_precision (float): - Required. A number between 0 and 1 that describes a minimum - mean average precision threshold. When the evaluation job - runs, if it calculates that your model version's predictions - from the recent interval have - [meanAveragePrecision][google.cloud.datalabeling.v1beta1.PrCurve.mean_average_precision] - below this threshold, then it sends an alert to your - specified email. - """ - - email = proto.Field( - proto.STRING, - number=1, - ) - min_acceptable_mean_average_precision = proto.Field( - proto.DOUBLE, - number=2, - ) - - -class Attempt(proto.Message): - r"""Records a failed evaluation job run. - - Attributes: - attempt_time (google.protobuf.timestamp_pb2.Timestamp): - - partial_failures (Sequence[google.rpc.status_pb2.Status]): - Details of errors that occurred. - """ - - attempt_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - partial_failures = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py deleted file mode 100644 index 84e04dc..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/human_annotation_config.py +++ /dev/null @@ -1,398 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'StringAggregationType', - 'HumanAnnotationConfig', - 'ImageClassificationConfig', - 'BoundingPolyConfig', - 'PolylineConfig', - 'SegmentationConfig', - 'VideoClassificationConfig', - 'ObjectDetectionConfig', - 'ObjectTrackingConfig', - 'EventConfig', - 'TextClassificationConfig', - 'SentimentConfig', - 'TextEntityExtractionConfig', - }, -) - - -class StringAggregationType(proto.Enum): - r"""""" - STRING_AGGREGATION_TYPE_UNSPECIFIED = 0 - MAJORITY_VOTE = 1 - UNANIMOUS_VOTE = 2 - NO_AGGREGATION = 3 - - -class HumanAnnotationConfig(proto.Message): - r"""Configuration for how human labeling task should be done. - - Attributes: - instruction (str): - Required. Instruction resource name. - annotated_dataset_display_name (str): - Required. A human-readable name for - AnnotatedDataset defined by users. Maximum of 64 - characters . - annotated_dataset_description (str): - Optional. A human-readable description for - AnnotatedDataset. The description can be up to - 10000 characters long. - label_group (str): - Optional. A human-readable label used to logically group - labeling tasks. This string must match the regular - expression ``[a-zA-Z\\d_-]{0,128}``. - language_code (str): - Optional. The Language of this question, as a - `BCP-47 `__. - Default value is en-US. Only need to set this when task is - language related. For example, French text classification. - replica_count (int): - Optional. Replication of questions. Each - question will be sent to up to this number of - contributors to label. Aggregated answers will - be returned. Default is set to 1. - For image related labeling, valid values are 1, - 3, 5. - question_duration (google.protobuf.duration_pb2.Duration): - Optional. Maximum duration for contributors - to answer a question. Maximum is 3600 seconds. - Default is 3600 seconds. - contributor_emails (Sequence[str]): - Optional. If you want your own labeling - contributors to manage and work on this labeling - request, you can set these contributors here. We - will give them access to the question types in - crowdcompute. Note that these emails must be - registered in crowdcompute worker UI: - https://crowd-compute.appspot.com/ - user_email_address (str): - Email of the user who started the labeling - task and should be notified by email. If empty - no notification will be sent. - """ - - instruction = proto.Field( - proto.STRING, - number=1, - ) - annotated_dataset_display_name = proto.Field( - proto.STRING, - number=2, - ) - annotated_dataset_description = proto.Field( - proto.STRING, - number=3, - ) - label_group = proto.Field( - proto.STRING, - number=4, - ) - language_code = proto.Field( - proto.STRING, - number=5, - ) - replica_count = proto.Field( - proto.INT32, - number=6, - ) - question_duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - contributor_emails = proto.RepeatedField( - proto.STRING, - number=9, - ) - user_email_address = proto.Field( - proto.STRING, - number=10, - ) - - -class ImageClassificationConfig(proto.Message): - r"""Config for image classification human labeling task. - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. - allow_multi_label (bool): - Optional. If allow_multi_label is true, contributors are - able to choose multiple labels for one image. - answer_aggregation_type (google.cloud.datalabeling_v1beta1.types.StringAggregationType): - Optional. The type of how to aggregate - answers. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - allow_multi_label = proto.Field( - proto.BOOL, - number=2, - ) - answer_aggregation_type = proto.Field( - proto.ENUM, - number=3, - enum='StringAggregationType', - ) - - -class BoundingPolyConfig(proto.Message): - r"""Config for image bounding poly (and bounding box) human - labeling task. - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. - instruction_message (str): - Optional. Instruction message showed on - contributors UI. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - instruction_message = proto.Field( - proto.STRING, - number=2, - ) - - -class PolylineConfig(proto.Message): - r"""Config for image polyline human labeling task. - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. - instruction_message (str): - Optional. Instruction message showed on - contributors UI. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - instruction_message = proto.Field( - proto.STRING, - number=2, - ) - - -class SegmentationConfig(proto.Message): - r"""Config for image segmentation - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. format: - projects/{project_id}/annotationSpecSets/{annotation_spec_set_id} - instruction_message (str): - Instruction message showed on labelers UI. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - instruction_message = proto.Field( - proto.STRING, - number=2, - ) - - -class VideoClassificationConfig(proto.Message): - r"""Config for video classification human labeling task. - Currently two types of video classification are supported: 1. - Assign labels on the entire video. - 2. Split the video into multiple video clips based on camera - shot, and assign labels on each video clip. - - Attributes: - annotation_spec_set_configs (Sequence[google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig.AnnotationSpecSetConfig]): - Required. The list of annotation spec set - configs. Since watching a video clip takes much - longer time than an image, we support label with - multiple AnnotationSpecSet at the same time. - Labels in each AnnotationSpecSet will be shown - in a group to contributors. Contributors can - select one or more (depending on whether to - allow multi label) from each group. - apply_shot_detection (bool): - Optional. Option to apply shot detection on - the video. - """ - - class AnnotationSpecSetConfig(proto.Message): - r"""Annotation spec set with the setting of allowing multi labels - or not. - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. - allow_multi_label (bool): - Optional. If allow_multi_label is true, contributors are - able to choose multiple labels from one annotation spec set. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - allow_multi_label = proto.Field( - proto.BOOL, - number=2, - ) - - annotation_spec_set_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=AnnotationSpecSetConfig, - ) - apply_shot_detection = proto.Field( - proto.BOOL, - number=2, - ) - - -class ObjectDetectionConfig(proto.Message): - r"""Config for video object detection human labeling task. - Object detection will be conducted on the images extracted from - the video, and those objects will be labeled with bounding - boxes. User need to specify the number of images to be extracted - per second as the extraction frame rate. - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. - extraction_frame_rate (float): - Required. Number of frames per second to be - extracted from the video. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - extraction_frame_rate = proto.Field( - proto.DOUBLE, - number=3, - ) - - -class ObjectTrackingConfig(proto.Message): - r"""Config for video object tracking human labeling task. - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - - -class EventConfig(proto.Message): - r"""Config for video event human labeling task. - - Attributes: - annotation_spec_sets (Sequence[str]): - Required. The list of annotation spec set - resource name. Similar to video classification, - we support selecting event from multiple - AnnotationSpecSet at the same time. - """ - - annotation_spec_sets = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class TextClassificationConfig(proto.Message): - r"""Config for text classification human labeling task. - - Attributes: - allow_multi_label (bool): - Optional. If allow_multi_label is true, contributors are - able to choose multiple labels for one text segment. - annotation_spec_set (str): - Required. Annotation spec set resource name. - sentiment_config (google.cloud.datalabeling_v1beta1.types.SentimentConfig): - Optional. Configs for sentiment selection. - """ - - allow_multi_label = proto.Field( - proto.BOOL, - number=1, - ) - annotation_spec_set = proto.Field( - proto.STRING, - number=2, - ) - sentiment_config = proto.Field( - proto.MESSAGE, - number=3, - message='SentimentConfig', - ) - - -class SentimentConfig(proto.Message): - r"""Config for setting up sentiments. - - Attributes: - enable_label_sentiment_selection (bool): - If set to true, contributors will have the - option to select sentiment of the label they - selected, to mark it as negative or positive - label. Default is false. - """ - - enable_label_sentiment_selection = proto.Field( - proto.BOOL, - number=1, - ) - - -class TextEntityExtractionConfig(proto.Message): - r"""Config for text entity extraction human labeling task. - - Attributes: - annotation_spec_set (str): - Required. Annotation spec set resource name. - """ - - annotation_spec_set = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py deleted file mode 100644 index 8f50b9f..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/instruction.py +++ /dev/null @@ -1,146 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.datalabeling_v1beta1.types import dataset -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'Instruction', - 'CsvInstruction', - 'PdfInstruction', - }, -) - - -class Instruction(proto.Message): - r"""Instruction of how to perform the labeling task for human - operators. Currently only PDF instruction is supported. - - Attributes: - name (str): - Output only. Instruction resource name, format: - projects/{project_id}/instructions/{instruction_id} - display_name (str): - Required. The display name of the - instruction. Maximum of 64 characters. - description (str): - Optional. User-provided description of the - instruction. The description can be up to 10000 - characters long. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation time of instruction. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last update time of instruction. - data_type (google.cloud.datalabeling_v1beta1.types.DataType): - Required. The data type of this instruction. - csv_instruction (google.cloud.datalabeling_v1beta1.types.CsvInstruction): - Deprecated: this instruction format is not supported any - more. Instruction from a CSV file, such as for - classification task. The CSV file should have exact two - columns, in the following format: - - - The first column is labeled data, such as an image - reference, text. - - The second column is comma separated labels associated - with data. - pdf_instruction (google.cloud.datalabeling_v1beta1.types.PdfInstruction): - Instruction from a PDF document. The PDF - should be in a Cloud Storage bucket. - blocking_resources (Sequence[str]): - Output only. The names of any related - resources that are blocking changes to the - instruction. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - data_type = proto.Field( - proto.ENUM, - number=6, - enum=dataset.DataType, - ) - csv_instruction = proto.Field( - proto.MESSAGE, - number=7, - message='CsvInstruction', - ) - pdf_instruction = proto.Field( - proto.MESSAGE, - number=9, - message='PdfInstruction', - ) - blocking_resources = proto.RepeatedField( - proto.STRING, - number=10, - ) - - -class CsvInstruction(proto.Message): - r"""Deprecated: this instruction format is not supported any - more. Instruction from a CSV file. - - Attributes: - gcs_file_uri (str): - CSV file for the instruction. Only gcs path - is allowed. - """ - - gcs_file_uri = proto.Field( - proto.STRING, - number=1, - ) - - -class PdfInstruction(proto.Message): - r"""Instruction from a PDF file. - - Attributes: - gcs_file_uri (str): - PDF file for the instruction. Only gcs path - is allowed. - """ - - gcs_file_uri = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py b/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py deleted file mode 100644 index 72a54b8..0000000 --- a/owl-bot-staging/v1beta1/google/cloud/datalabeling_v1beta1/types/operations.py +++ /dev/null @@ -1,549 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import human_annotation_config -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datalabeling.v1beta1', - manifest={ - 'ImportDataOperationResponse', - 'ExportDataOperationResponse', - 'ImportDataOperationMetadata', - 'ExportDataOperationMetadata', - 'LabelOperationMetadata', - 'LabelImageClassificationOperationMetadata', - 'LabelImageBoundingBoxOperationMetadata', - 'LabelImageOrientedBoundingBoxOperationMetadata', - 'LabelImageBoundingPolyOperationMetadata', - 'LabelImagePolylineOperationMetadata', - 'LabelImageSegmentationOperationMetadata', - 'LabelVideoClassificationOperationMetadata', - 'LabelVideoObjectDetectionOperationMetadata', - 'LabelVideoObjectTrackingOperationMetadata', - 'LabelVideoEventOperationMetadata', - 'LabelTextClassificationOperationMetadata', - 'LabelTextEntityExtractionOperationMetadata', - 'CreateInstructionMetadata', - }, -) - - -class ImportDataOperationResponse(proto.Message): - r"""Response used for ImportData longrunning operation. - - Attributes: - dataset (str): - Ouptut only. The name of imported dataset. - total_count (int): - Output only. Total number of examples - requested to import - import_count (int): - Output only. Number of examples imported - successfully. - """ - - dataset = proto.Field( - proto.STRING, - number=1, - ) - total_count = proto.Field( - proto.INT32, - number=2, - ) - import_count = proto.Field( - proto.INT32, - number=3, - ) - - -class ExportDataOperationResponse(proto.Message): - r"""Response used for ExportDataset longrunning operation. - - Attributes: - dataset (str): - Ouptut only. The name of dataset. "projects/*/datasets/*". - total_count (int): - Output only. Total number of examples - requested to export - export_count (int): - Output only. Number of examples exported - successfully. - label_stats (google.cloud.datalabeling_v1beta1.types.LabelStats): - Output only. Statistic infos of labels in the - exported dataset. - output_config (google.cloud.datalabeling_v1beta1.types.OutputConfig): - Output only. output_config in the ExportData request. - """ - - dataset = proto.Field( - proto.STRING, - number=1, - ) - total_count = proto.Field( - proto.INT32, - number=2, - ) - export_count = proto.Field( - proto.INT32, - number=3, - ) - label_stats = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_dataset.LabelStats, - ) - output_config = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_dataset.OutputConfig, - ) - - -class ImportDataOperationMetadata(proto.Message): - r"""Metadata of an ImportData operation. - - Attributes: - dataset (str): - Output only. The name of imported dataset. - "projects/*/datasets/*". - partial_failures (Sequence[google.rpc.status_pb2.Status]): - Output only. Partial failures encountered. - E.g. single files that couldn't be read. - Status details field will contain standard GCP - error details. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when import dataset - request was created. - """ - - dataset = proto.Field( - proto.STRING, - number=1, - ) - partial_failures = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - create_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class ExportDataOperationMetadata(proto.Message): - r"""Metadata of an ExportData operation. - - Attributes: - dataset (str): - Output only. The name of dataset to be exported. - "projects/*/datasets/*". - partial_failures (Sequence[google.rpc.status_pb2.Status]): - Output only. Partial failures encountered. - E.g. single files that couldn't be read. - Status details field will contain standard GCP - error details. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when export dataset - request was created. - """ - - dataset = proto.Field( - proto.STRING, - number=1, - ) - partial_failures = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - create_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class LabelOperationMetadata(proto.Message): - r"""Metadata of a labeling operation, such as LabelImage or - LabelVideo. Next tag: 20 - - Attributes: - image_classification_details (google.cloud.datalabeling_v1beta1.types.LabelImageClassificationOperationMetadata): - Details of label image classification - operation. - image_bounding_box_details (google.cloud.datalabeling_v1beta1.types.LabelImageBoundingBoxOperationMetadata): - Details of label image bounding box - operation. - image_bounding_poly_details (google.cloud.datalabeling_v1beta1.types.LabelImageBoundingPolyOperationMetadata): - Details of label image bounding poly - operation. - image_oriented_bounding_box_details (google.cloud.datalabeling_v1beta1.types.LabelImageOrientedBoundingBoxOperationMetadata): - Details of label image oriented bounding box - operation. - image_polyline_details (google.cloud.datalabeling_v1beta1.types.LabelImagePolylineOperationMetadata): - Details of label image polyline operation. - image_segmentation_details (google.cloud.datalabeling_v1beta1.types.LabelImageSegmentationOperationMetadata): - Details of label image segmentation - operation. - video_classification_details (google.cloud.datalabeling_v1beta1.types.LabelVideoClassificationOperationMetadata): - Details of label video classification - operation. - video_object_detection_details (google.cloud.datalabeling_v1beta1.types.LabelVideoObjectDetectionOperationMetadata): - Details of label video object detection - operation. - video_object_tracking_details (google.cloud.datalabeling_v1beta1.types.LabelVideoObjectTrackingOperationMetadata): - Details of label video object tracking - operation. - video_event_details (google.cloud.datalabeling_v1beta1.types.LabelVideoEventOperationMetadata): - Details of label video event operation. - text_classification_details (google.cloud.datalabeling_v1beta1.types.LabelTextClassificationOperationMetadata): - Details of label text classification - operation. - text_entity_extraction_details (google.cloud.datalabeling_v1beta1.types.LabelTextEntityExtractionOperationMetadata): - Details of label text entity extraction - operation. - progress_percent (int): - Output only. Progress of label operation. Range: [0, 100]. - partial_failures (Sequence[google.rpc.status_pb2.Status]): - Output only. Partial failures encountered. - E.g. single files that couldn't be read. - Status details field will contain standard GCP - error details. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when labeling request - was created. - """ - - image_classification_details = proto.Field( - proto.MESSAGE, - number=3, - oneof='details', - message='LabelImageClassificationOperationMetadata', - ) - image_bounding_box_details = proto.Field( - proto.MESSAGE, - number=4, - oneof='details', - message='LabelImageBoundingBoxOperationMetadata', - ) - image_bounding_poly_details = proto.Field( - proto.MESSAGE, - number=11, - oneof='details', - message='LabelImageBoundingPolyOperationMetadata', - ) - image_oriented_bounding_box_details = proto.Field( - proto.MESSAGE, - number=14, - oneof='details', - message='LabelImageOrientedBoundingBoxOperationMetadata', - ) - image_polyline_details = proto.Field( - proto.MESSAGE, - number=12, - oneof='details', - message='LabelImagePolylineOperationMetadata', - ) - image_segmentation_details = proto.Field( - proto.MESSAGE, - number=15, - oneof='details', - message='LabelImageSegmentationOperationMetadata', - ) - video_classification_details = proto.Field( - proto.MESSAGE, - number=5, - oneof='details', - message='LabelVideoClassificationOperationMetadata', - ) - video_object_detection_details = proto.Field( - proto.MESSAGE, - number=6, - oneof='details', - message='LabelVideoObjectDetectionOperationMetadata', - ) - video_object_tracking_details = proto.Field( - proto.MESSAGE, - number=7, - oneof='details', - message='LabelVideoObjectTrackingOperationMetadata', - ) - video_event_details = proto.Field( - proto.MESSAGE, - number=8, - oneof='details', - message='LabelVideoEventOperationMetadata', - ) - text_classification_details = proto.Field( - proto.MESSAGE, - number=9, - oneof='details', - message='LabelTextClassificationOperationMetadata', - ) - text_entity_extraction_details = proto.Field( - proto.MESSAGE, - number=13, - oneof='details', - message='LabelTextEntityExtractionOperationMetadata', - ) - progress_percent = proto.Field( - proto.INT32, - number=1, - ) - partial_failures = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - create_time = proto.Field( - proto.MESSAGE, - number=16, - message=timestamp_pb2.Timestamp, - ) - - -class LabelImageClassificationOperationMetadata(proto.Message): - r"""Metadata of a LabelImageClassification operation. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelImageBoundingBoxOperationMetadata(proto.Message): - r"""Details of a LabelImageBoundingBox operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelImageOrientedBoundingBoxOperationMetadata(proto.Message): - r"""Details of a LabelImageOrientedBoundingBox operation - metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelImageBoundingPolyOperationMetadata(proto.Message): - r"""Details of LabelImageBoundingPoly operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelImagePolylineOperationMetadata(proto.Message): - r"""Details of LabelImagePolyline operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelImageSegmentationOperationMetadata(proto.Message): - r"""Details of a LabelImageSegmentation operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelVideoClassificationOperationMetadata(proto.Message): - r"""Details of a LabelVideoClassification operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelVideoObjectDetectionOperationMetadata(proto.Message): - r"""Details of a LabelVideoObjectDetection operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelVideoObjectTrackingOperationMetadata(proto.Message): - r"""Details of a LabelVideoObjectTracking operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelVideoEventOperationMetadata(proto.Message): - r"""Details of a LabelVideoEvent operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelTextClassificationOperationMetadata(proto.Message): - r"""Details of a LabelTextClassification operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class LabelTextEntityExtractionOperationMetadata(proto.Message): - r"""Details of a LabelTextEntityExtraction operation metadata. - - Attributes: - basic_config (google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig): - Basic human annotation config used in - labeling request. - """ - - basic_config = proto.Field( - proto.MESSAGE, - number=1, - message=human_annotation_config.HumanAnnotationConfig, - ) - - -class CreateInstructionMetadata(proto.Message): - r"""Metadata of a CreateInstruction operation. - - Attributes: - instruction (str): - The name of the created Instruction. - projects/{project_id}/instructions/{instruction_id} - partial_failures (Sequence[google.rpc.status_pb2.Status]): - Partial failures encountered. - E.g. single files that couldn't be read. - Status details field will contain standard GCP - error details. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when create instruction request was - created. - """ - - instruction = proto.Field( - proto.STRING, - number=1, - ) - partial_failures = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - create_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py deleted file mode 100644 index 240f3d4..0000000 --- a/owl-bot-staging/v1beta1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/datalabeling_v1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py deleted file mode 100644 index 4f2e670..0000000 --- a/owl-bot-staging/v1beta1/scripts/fixup_datalabeling_v1beta1_keywords.py +++ /dev/null @@ -1,209 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 datalabelingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_annotation_spec_set': ('parent', 'annotation_spec_set', ), - 'create_dataset': ('parent', 'dataset', ), - 'create_evaluation_job': ('parent', 'job', ), - 'create_instruction': ('parent', 'instruction', ), - 'delete_annotated_dataset': ('name', ), - 'delete_annotation_spec_set': ('name', ), - 'delete_dataset': ('name', ), - 'delete_evaluation_job': ('name', ), - 'delete_instruction': ('name', ), - 'export_data': ('name', 'annotated_dataset', 'output_config', 'filter', 'user_email_address', ), - 'get_annotated_dataset': ('name', ), - 'get_annotation_spec_set': ('name', ), - 'get_data_item': ('name', ), - 'get_dataset': ('name', ), - 'get_evaluation': ('name', ), - 'get_evaluation_job': ('name', ), - 'get_example': ('name', 'filter', ), - 'get_instruction': ('name', ), - 'import_data': ('name', 'input_config', 'user_email_address', ), - 'label_image': ('parent', 'basic_config', 'feature', 'image_classification_config', 'bounding_poly_config', 'polyline_config', 'segmentation_config', ), - 'label_text': ('parent', 'basic_config', 'feature', 'text_classification_config', 'text_entity_extraction_config', ), - 'label_video': ('parent', 'basic_config', 'feature', 'video_classification_config', 'object_detection_config', 'object_tracking_config', 'event_config', ), - 'list_annotated_datasets': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_annotation_spec_sets': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_data_items': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_datasets': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_evaluation_jobs': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_examples': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_instructions': ('parent', 'filter', 'page_size', 'page_token', ), - 'pause_evaluation_job': ('name', ), - 'resume_evaluation_job': ('name', ), - 'search_evaluations': ('parent', 'filter', 'page_size', 'page_token', ), - 'search_example_comparisons': ('parent', 'page_size', 'page_token', ), - 'update_evaluation_job': ('evaluation_job', '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=datalabelingCallTransformer(), -): - """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 datalabeling 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py deleted file mode 100644 index 68a9f75..0000000 --- a/owl-bot-staging/v1beta1/setup.py +++ /dev/null @@ -1,54 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-datalabeling', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py deleted file mode 100644 index b7fa677..0000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py +++ /dev/null @@ -1,10939 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -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_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.datalabeling_v1beta1.services.data_labeling_service import DataLabelingServiceAsyncClient -from google.cloud.datalabeling_v1beta1.services.data_labeling_service import DataLabelingServiceClient -from google.cloud.datalabeling_v1beta1.services.data_labeling_service import pagers -from google.cloud.datalabeling_v1beta1.services.data_labeling_service import transports -from google.cloud.datalabeling_v1beta1.services.data_labeling_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.datalabeling_v1beta1.types import annotation -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import annotation_spec_set as gcd_annotation_spec_set -from google.cloud.datalabeling_v1beta1.types import data_labeling_service -from google.cloud.datalabeling_v1beta1.types import data_payloads -from google.cloud.datalabeling_v1beta1.types import dataset -from google.cloud.datalabeling_v1beta1.types import dataset as gcd_dataset -from google.cloud.datalabeling_v1beta1.types import evaluation -from google.cloud.datalabeling_v1beta1.types import evaluation_job -from google.cloud.datalabeling_v1beta1.types import evaluation_job as gcd_evaluation_job -from google.cloud.datalabeling_v1beta1.types import human_annotation_config -from google.cloud.datalabeling_v1beta1.types import instruction -from google.cloud.datalabeling_v1beta1.types import instruction as gcd_instruction -from google.cloud.datalabeling_v1beta1.types import operations -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DataLabelingServiceClient._get_default_mtls_endpoint(None) is None - assert DataLabelingServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DataLabelingServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DataLabelingServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DataLabelingServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DataLabelingServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - DataLabelingServiceClient, - DataLabelingServiceAsyncClient, -]) -def test_data_labeling_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'datalabeling.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DataLabelingServiceGrpcTransport, "grpc"), - (transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_labeling_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", [ - DataLabelingServiceClient, - DataLabelingServiceAsyncClient, -]) -def test_data_labeling_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'datalabeling.googleapis.com:443' - - -def test_data_labeling_service_client_get_transport_class(): - transport = DataLabelingServiceClient.get_transport_class() - available_transports = [ - transports.DataLabelingServiceGrpcTransport, - ] - assert transport in available_transports - - transport = DataLabelingServiceClient.get_transport_class("grpc") - assert transport == transports.DataLabelingServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc"), - (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(DataLabelingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceClient)) -@mock.patch.object(DataLabelingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceAsyncClient)) -def test_data_labeling_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(DataLabelingServiceClient, '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(DataLabelingServiceClient, '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(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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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() - 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc", "true"), - (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc", "false"), - (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(DataLabelingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceClient)) -@mock.patch.object(DataLabelingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataLabelingServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_data_labeling_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - 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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc"), - (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_labeling_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataLabelingServiceClient, transports.DataLabelingServiceGrpcTransport, "grpc"), - (DataLabelingServiceAsyncClient, transports.DataLabelingServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_labeling_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_data_labeling_service_client_client_options_from_dict(): - with mock.patch('google.cloud.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DataLabelingServiceClient( - 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, - ) - - -def test_create_dataset(transport: str = 'grpc', request_type=data_labeling_service.CreateDatasetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - data_item_count=1584, - ) - response = client.create_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] == data_labeling_service.CreateDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - assert response.data_item_count == 1584 - - -def test_create_dataset_from_dict(): - test_create_dataset(request_type=dict) - - -def test_create_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 = DataLabelingServiceClient( - 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_dataset), - '__call__') as call: - client.create_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateDatasetRequest() - - -@pytest.mark.asyncio -async def test_create_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateDatasetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - data_item_count=1584, - )) - response = await client.create_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - assert response.data_item_count == 1584 - - -@pytest.mark.asyncio -async def test_create_dataset_async_from_dict(): - await test_create_dataset_async(request_type=dict) - - -def test_create_dataset_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateDatasetRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - call.return_value = gcd_dataset.Dataset() - client.create_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', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_dataset_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateDatasetRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_dataset.Dataset()) - await client.create_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', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_create_dataset_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_dataset.Dataset() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_dataset( - parent='parent_value', - dataset=gcd_dataset.Dataset(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] - assert args[0].parent == 'parent_value' - assert args[0].dataset == gcd_dataset.Dataset(name='name_value') - - -def test_create_dataset_flattened_error(): - client = DataLabelingServiceClient( - 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_dataset( - data_labeling_service.CreateDatasetRequest(), - parent='parent_value', - dataset=gcd_dataset.Dataset(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_dataset_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_dataset.Dataset() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_dataset.Dataset()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_dataset( - parent='parent_value', - dataset=gcd_dataset.Dataset(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] - assert args[0].parent == 'parent_value' - assert args[0].dataset == gcd_dataset.Dataset(name='name_value') - - -@pytest.mark.asyncio -async def test_create_dataset_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_dataset( - data_labeling_service.CreateDatasetRequest(), - parent='parent_value', - dataset=gcd_dataset.Dataset(name='name_value'), - ) - - -def test_get_dataset(transport: str = 'grpc', request_type=data_labeling_service.GetDatasetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - data_item_count=1584, - ) - response = client.get_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] == data_labeling_service.GetDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - assert response.data_item_count == 1584 - - -def test_get_dataset_from_dict(): - test_get_dataset(request_type=dict) - - -def test_get_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 = DataLabelingServiceClient( - 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), - '__call__') as call: - client.get_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetDatasetRequest() - - -@pytest.mark.asyncio -async def test_get_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetDatasetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - data_item_count=1584, - )) - response = await client.get_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - assert response.data_item_count == 1584 - - -@pytest.mark.asyncio -async def test_get_dataset_async_from_dict(): - await test_get_dataset_async(request_type=dict) - - -def test_get_dataset_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetDatasetRequest() - - 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), - '__call__') as call: - call.return_value = dataset.Dataset() - client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_dataset_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetDatasetRequest() - - 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), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) - await client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_dataset_flattened(): - client = DataLabelingServiceClient( - 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), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Dataset() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_dataset( - 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] - assert args[0].name == 'name_value' - - -def test_get_dataset_flattened_error(): - client = DataLabelingServiceClient( - 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( - data_labeling_service.GetDatasetRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_dataset_flattened_async(): - client = DataLabelingServiceAsyncClient( - 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), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Dataset() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_dataset( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_dataset_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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( - data_labeling_service.GetDatasetRequest(), - name='name_value', - ) - - -def test_list_datasets(transport: str = 'grpc', request_type=data_labeling_service.ListDatasetsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListDatasetsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListDatasetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDatasetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_datasets_from_dict(): - test_list_datasets(request_type=dict) - - -def test_list_datasets_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 = DataLabelingServiceClient( - 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_datasets), - '__call__') as call: - client.list_datasets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListDatasetsRequest() - - -@pytest.mark.asyncio -async def test_list_datasets_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListDatasetsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDatasetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListDatasetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDatasetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_datasets_async_from_dict(): - await test_list_datasets_async(request_type=dict) - - -def test_list_datasets_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListDatasetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - call.return_value = data_labeling_service.ListDatasetsResponse() - client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_datasets_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListDatasetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDatasetsResponse()) - await client.list_datasets(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_datasets_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListDatasetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_datasets( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_datasets_flattened_error(): - client = DataLabelingServiceClient( - 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_datasets( - data_labeling_service.ListDatasetsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_datasets_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListDatasetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDatasetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_datasets( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_datasets_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_datasets( - data_labeling_service.ListDatasetsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_datasets_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_datasets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, dataset.Dataset) - for i in results) - -def test_list_datasets_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - RuntimeError, - ) - pages = list(client.list_datasets(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_datasets_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_datasets(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, dataset.Dataset) - for i in responses) - -@pytest.mark.asyncio -async def test_list_datasets_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_datasets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_dataset(transport: str = 'grpc', request_type=data_labeling_service.DeleteDatasetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_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] == data_labeling_service.DeleteDatasetRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_dataset_from_dict(): - test_delete_dataset(request_type=dict) - - -def test_delete_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 = DataLabelingServiceClient( - 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_dataset), - '__call__') as call: - client.delete_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteDatasetRequest() - - -@pytest.mark.asyncio -async def test_delete_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteDatasetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteDatasetRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_dataset_async_from_dict(): - await test_delete_dataset_async(request_type=dict) - - -def test_delete_dataset_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteDatasetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - call.return_value = None - client.delete_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_dataset_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteDatasetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_dataset_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_dataset( - 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] - assert args[0].name == 'name_value' - - -def test_delete_dataset_flattened_error(): - client = DataLabelingServiceClient( - 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_dataset( - data_labeling_service.DeleteDatasetRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_dataset_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_dataset( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_dataset_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_dataset( - data_labeling_service.DeleteDatasetRequest(), - name='name_value', - ) - - -def test_import_data(transport: str = 'grpc', request_type=data_labeling_service.ImportDataRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ImportDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_data_from_dict(): - test_import_data(request_type=dict) - - -def test_import_data_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 = DataLabelingServiceClient( - 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_data), - '__call__') as call: - client.import_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ImportDataRequest() - - -@pytest.mark.asyncio -async def test_import_data_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ImportDataRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data), - '__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_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ImportDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_data_async_from_dict(): - await test_import_data_async(request_type=dict) - - -def test_import_data_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ImportDataRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_import_data_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ImportDataRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_data(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_import_data_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_data), - '__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_data( - name='name_value', - input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_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] - assert args[0].name == 'name_value' - assert args[0].input_config == dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')) - - -def test_import_data_flattened_error(): - client = DataLabelingServiceClient( - 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_data( - data_labeling_service.ImportDataRequest(), - name='name_value', - input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')), - ) - - -@pytest.mark.asyncio -async def test_import_data_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_data), - '__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_data( - name='name_value', - input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].input_config == dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')) - - -@pytest.mark.asyncio -async def test_import_data_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_data( - data_labeling_service.ImportDataRequest(), - name='name_value', - input_config=dataset.InputConfig(text_metadata=dataset.TextMetadata(language_code='language_code_value')), - ) - - -def test_export_data(transport: str = 'grpc', request_type=data_labeling_service.ExportDataRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ExportDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_data_from_dict(): - test_export_data(request_type=dict) - - -def test_export_data_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 = DataLabelingServiceClient( - 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.export_data), - '__call__') as call: - client.export_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ExportDataRequest() - - -@pytest.mark.asyncio -async def test_export_data_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ExportDataRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_data), - '__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.export_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ExportDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_data_async_from_dict(): - await test_export_data_async(request_type=dict) - - -def test_export_data_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ExportDataRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_export_data_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ExportDataRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_data(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_export_data_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_data), - '__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.export_data( - name='name_value', - annotated_dataset='annotated_dataset_value', - filter='filter_value', - output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_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] - assert args[0].name == 'name_value' - assert args[0].annotated_dataset == 'annotated_dataset_value' - assert args[0].filter == 'filter_value' - assert args[0].output_config == dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')) - - -def test_export_data_flattened_error(): - client = DataLabelingServiceClient( - 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.export_data( - data_labeling_service.ExportDataRequest(), - name='name_value', - annotated_dataset='annotated_dataset_value', - filter='filter_value', - output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')), - ) - - -@pytest.mark.asyncio -async def test_export_data_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_data), - '__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.export_data( - name='name_value', - annotated_dataset='annotated_dataset_value', - filter='filter_value', - output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].annotated_dataset == 'annotated_dataset_value' - assert args[0].filter == 'filter_value' - assert args[0].output_config == dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')) - - -@pytest.mark.asyncio -async def test_export_data_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.export_data( - data_labeling_service.ExportDataRequest(), - name='name_value', - annotated_dataset='annotated_dataset_value', - filter='filter_value', - output_config=dataset.OutputConfig(gcs_destination=dataset.GcsDestination(output_uri='output_uri_value')), - ) - - -def test_get_data_item(transport: str = 'grpc', request_type=data_labeling_service.GetDataItemRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DataItem( - name='name_value', - image_payload=data_payloads.ImagePayload(mime_type='mime_type_value'), - ) - response = client.get_data_item(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetDataItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DataItem) - assert response.name == 'name_value' - - -def test_get_data_item_from_dict(): - test_get_data_item(request_type=dict) - - -def test_get_data_item_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 = DataLabelingServiceClient( - 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_data_item), - '__call__') as call: - client.get_data_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetDataItemRequest() - - -@pytest.mark.asyncio -async def test_get_data_item_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetDataItemRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.DataItem( - name='name_value', - )) - response = await client.get_data_item(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetDataItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.DataItem) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_data_item_async_from_dict(): - await test_get_data_item_async(request_type=dict) - - -def test_get_data_item_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetDataItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_item), - '__call__') as call: - call.return_value = dataset.DataItem() - client.get_data_item(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_data_item_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetDataItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_item), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DataItem()) - await client.get_data_item(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_data_item_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DataItem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_data_item( - 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] - assert args[0].name == 'name_value' - - -def test_get_data_item_flattened_error(): - client = DataLabelingServiceClient( - 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_data_item( - data_labeling_service.GetDataItemRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_data_item_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.DataItem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.DataItem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_data_item( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_data_item_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_data_item( - data_labeling_service.GetDataItemRequest(), - name='name_value', - ) - - -def test_list_data_items(transport: str = 'grpc', request_type=data_labeling_service.ListDataItemsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListDataItemsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_data_items(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListDataItemsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataItemsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_data_items_from_dict(): - test_list_data_items(request_type=dict) - - -def test_list_data_items_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 = DataLabelingServiceClient( - 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_data_items), - '__call__') as call: - client.list_data_items() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListDataItemsRequest() - - -@pytest.mark.asyncio -async def test_list_data_items_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListDataItemsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDataItemsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_data_items(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListDataItemsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataItemsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_data_items_async_from_dict(): - await test_list_data_items_async(request_type=dict) - - -def test_list_data_items_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListDataItemsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__') as call: - call.return_value = data_labeling_service.ListDataItemsResponse() - client.list_data_items(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_data_items_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListDataItemsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDataItemsResponse()) - await client.list_data_items(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_data_items_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListDataItemsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_data_items( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_data_items_flattened_error(): - client = DataLabelingServiceClient( - 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_data_items( - data_labeling_service.ListDataItemsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_data_items_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListDataItemsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListDataItemsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_data_items( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_data_items_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_data_items( - data_labeling_service.ListDataItemsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_data_items_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - dataset.DataItem(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[], - next_page_token='def', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_data_items(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, dataset.DataItem) - for i in results) - -def test_list_data_items_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - dataset.DataItem(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[], - next_page_token='def', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - ], - ), - RuntimeError, - ) - pages = list(client.list_data_items(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_data_items_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - dataset.DataItem(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[], - next_page_token='def', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_data_items(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, dataset.DataItem) - for i in responses) - -@pytest.mark.asyncio -async def test_list_data_items_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_items), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - dataset.DataItem(), - ], - next_page_token='abc', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[], - next_page_token='def', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListDataItemsResponse( - data_items=[ - dataset.DataItem(), - dataset.DataItem(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_data_items(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_annotated_dataset(transport: str = 'grpc', request_type=data_labeling_service.GetAnnotatedDatasetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotated_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.AnnotatedDataset( - name='name_value', - display_name='display_name_value', - description='description_value', - annotation_source=annotation.AnnotationSource.OPERATOR, - annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, - example_count=1396, - completed_example_count=2448, - blocking_resources=['blocking_resources_value'], - ) - response = client.get_annotated_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] == data_labeling_service.GetAnnotatedDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.AnnotatedDataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.annotation_source == annotation.AnnotationSource.OPERATOR - assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION - assert response.example_count == 1396 - assert response.completed_example_count == 2448 - assert response.blocking_resources == ['blocking_resources_value'] - - -def test_get_annotated_dataset_from_dict(): - test_get_annotated_dataset(request_type=dict) - - -def test_get_annotated_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 = DataLabelingServiceClient( - 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_annotated_dataset), - '__call__') as call: - client.get_annotated_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetAnnotatedDatasetRequest() - - -@pytest.mark.asyncio -async def test_get_annotated_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetAnnotatedDatasetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotated_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.AnnotatedDataset( - name='name_value', - display_name='display_name_value', - description='description_value', - annotation_source=annotation.AnnotationSource.OPERATOR, - annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, - example_count=1396, - completed_example_count=2448, - blocking_resources=['blocking_resources_value'], - )) - response = await client.get_annotated_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetAnnotatedDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.AnnotatedDataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.annotation_source == annotation.AnnotationSource.OPERATOR - assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION - assert response.example_count == 1396 - assert response.completed_example_count == 2448 - assert response.blocking_resources == ['blocking_resources_value'] - - -@pytest.mark.asyncio -async def test_get_annotated_dataset_async_from_dict(): - await test_get_annotated_dataset_async(request_type=dict) - - -def test_get_annotated_dataset_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetAnnotatedDatasetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotated_dataset), - '__call__') as call: - call.return_value = dataset.AnnotatedDataset() - client.get_annotated_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_annotated_dataset_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetAnnotatedDatasetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotated_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.AnnotatedDataset()) - await client.get_annotated_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_annotated_dataset_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotated_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.AnnotatedDataset() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_annotated_dataset( - 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] - assert args[0].name == 'name_value' - - -def test_get_annotated_dataset_flattened_error(): - client = DataLabelingServiceClient( - 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_annotated_dataset( - data_labeling_service.GetAnnotatedDatasetRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_annotated_dataset_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotated_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.AnnotatedDataset() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.AnnotatedDataset()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_annotated_dataset( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_annotated_dataset_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_annotated_dataset( - data_labeling_service.GetAnnotatedDatasetRequest(), - name='name_value', - ) - - -def test_list_annotated_datasets(transport: str = 'grpc', request_type=data_labeling_service.ListAnnotatedDatasetsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotated_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_annotated_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListAnnotatedDatasetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnnotatedDatasetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_annotated_datasets_from_dict(): - test_list_annotated_datasets(request_type=dict) - - -def test_list_annotated_datasets_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 = DataLabelingServiceClient( - 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_annotated_datasets), - '__call__') as call: - client.list_annotated_datasets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListAnnotatedDatasetsRequest() - - -@pytest.mark.asyncio -async def test_list_annotated_datasets_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListAnnotatedDatasetsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotated_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotatedDatasetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_annotated_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListAnnotatedDatasetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnnotatedDatasetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_annotated_datasets_async_from_dict(): - await test_list_annotated_datasets_async(request_type=dict) - - -def test_list_annotated_datasets_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListAnnotatedDatasetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__') as call: - call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse() - client.list_annotated_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_annotated_datasets_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListAnnotatedDatasetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotatedDatasetsResponse()) - await client.list_annotated_datasets(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_annotated_datasets_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_annotated_datasets( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_annotated_datasets_flattened_error(): - client = DataLabelingServiceClient( - 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_annotated_datasets( - data_labeling_service.ListAnnotatedDatasetsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_annotated_datasets_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListAnnotatedDatasetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotatedDatasetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_annotated_datasets( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_annotated_datasets_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_annotated_datasets( - data_labeling_service.ListAnnotatedDatasetsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_annotated_datasets_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_annotated_datasets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, dataset.AnnotatedDataset) - for i in results) - -def test_list_annotated_datasets_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - ), - RuntimeError, - ) - pages = list(client.list_annotated_datasets(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_annotated_datasets_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_annotated_datasets(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, dataset.AnnotatedDataset) - for i in responses) - -@pytest.mark.asyncio -async def test_list_annotated_datasets_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotated_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotatedDatasetsResponse( - annotated_datasets=[ - dataset.AnnotatedDataset(), - dataset.AnnotatedDataset(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_annotated_datasets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_annotated_dataset(transport: str = 'grpc', request_type=data_labeling_service.DeleteAnnotatedDatasetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotated_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_annotated_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] == data_labeling_service.DeleteAnnotatedDatasetRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_annotated_dataset_from_dict(): - test_delete_annotated_dataset(request_type=dict) - - -def test_delete_annotated_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 = DataLabelingServiceClient( - 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_annotated_dataset), - '__call__') as call: - client.delete_annotated_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteAnnotatedDatasetRequest() - - -@pytest.mark.asyncio -async def test_delete_annotated_dataset_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteAnnotatedDatasetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotated_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_annotated_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteAnnotatedDatasetRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_annotated_dataset_async_from_dict(): - await test_delete_annotated_dataset_async(request_type=dict) - - -def test_delete_annotated_dataset_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteAnnotatedDatasetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_annotated_dataset), - '__call__') as call: - call.return_value = None - client.delete_annotated_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_annotated_dataset_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteAnnotatedDatasetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_annotated_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_annotated_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_label_image(transport: str = 'grpc', request_type=data_labeling_service.LabelImageRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_image), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.label_image(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelImageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_label_image_from_dict(): - test_label_image(request_type=dict) - - -def test_label_image_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 = DataLabelingServiceClient( - 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.label_image), - '__call__') as call: - client.label_image() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelImageRequest() - - -@pytest.mark.asyncio -async def test_label_image_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.LabelImageRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_image), - '__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.label_image(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelImageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_label_image_async_from_dict(): - await test_label_image_async(request_type=dict) - - -def test_label_image_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.LabelImageRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_image), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.label_image(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_label_image_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.LabelImageRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_image), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.label_image(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_label_image_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_image), - '__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.label_image( - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') - assert args[0].feature == data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION - - -def test_label_image_flattened_error(): - client = DataLabelingServiceClient( - 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.label_image( - data_labeling_service.LabelImageRequest(), - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, - ) - - -@pytest.mark.asyncio -async def test_label_image_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_image), - '__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.label_image( - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') - assert args[0].feature == data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION - - -@pytest.mark.asyncio -async def test_label_image_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.label_image( - data_labeling_service.LabelImageRequest(), - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelImageRequest.Feature.CLASSIFICATION, - ) - - -def test_label_video(transport: str = 'grpc', request_type=data_labeling_service.LabelVideoRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.label_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_label_video_from_dict(): - test_label_video(request_type=dict) - - -def test_label_video_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 = DataLabelingServiceClient( - 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.label_video), - '__call__') as call: - client.label_video() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelVideoRequest() - - -@pytest.mark.asyncio -async def test_label_video_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.LabelVideoRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_video), - '__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.label_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_label_video_async_from_dict(): - await test_label_video_async(request_type=dict) - - -def test_label_video_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.LabelVideoRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_video), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.label_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_label_video_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.LabelVideoRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_video), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.label_video(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_label_video_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_video), - '__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.label_video( - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') - assert args[0].feature == data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION - - -def test_label_video_flattened_error(): - client = DataLabelingServiceClient( - 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.label_video( - data_labeling_service.LabelVideoRequest(), - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, - ) - - -@pytest.mark.asyncio -async def test_label_video_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_video), - '__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.label_video( - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') - assert args[0].feature == data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION - - -@pytest.mark.asyncio -async def test_label_video_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.label_video( - data_labeling_service.LabelVideoRequest(), - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelVideoRequest.Feature.CLASSIFICATION, - ) - - -def test_label_text(transport: str = 'grpc', request_type=data_labeling_service.LabelTextRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_text), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.label_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_label_text_from_dict(): - test_label_text(request_type=dict) - - -def test_label_text_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 = DataLabelingServiceClient( - 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.label_text), - '__call__') as call: - client.label_text() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelTextRequest() - - -@pytest.mark.asyncio -async def test_label_text_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.LabelTextRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_text), - '__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.label_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.LabelTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_label_text_async_from_dict(): - await test_label_text_async(request_type=dict) - - -def test_label_text_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.LabelTextRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_text), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.label_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_label_text_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.LabelTextRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_text), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.label_text(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_label_text_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_text), - '__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.label_text( - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') - assert args[0].feature == data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION - - -def test_label_text_flattened_error(): - client = DataLabelingServiceClient( - 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.label_text( - data_labeling_service.LabelTextRequest(), - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, - ) - - -@pytest.mark.asyncio -async def test_label_text_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.label_text), - '__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.label_text( - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].basic_config == human_annotation_config.HumanAnnotationConfig(instruction='instruction_value') - assert args[0].feature == data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION - - -@pytest.mark.asyncio -async def test_label_text_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.label_text( - data_labeling_service.LabelTextRequest(), - parent='parent_value', - basic_config=human_annotation_config.HumanAnnotationConfig(instruction='instruction_value'), - feature=data_labeling_service.LabelTextRequest.Feature.TEXT_CLASSIFICATION, - ) - - -def test_get_example(transport: str = 'grpc', request_type=data_labeling_service.GetExampleRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_example), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Example( - name='name_value', - image_payload=data_payloads.ImagePayload(mime_type='mime_type_value'), - ) - response = client.get_example(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetExampleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.Example) - assert response.name == 'name_value' - - -def test_get_example_from_dict(): - test_get_example(request_type=dict) - - -def test_get_example_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 = DataLabelingServiceClient( - 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_example), - '__call__') as call: - client.get_example() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetExampleRequest() - - -@pytest.mark.asyncio -async def test_get_example_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetExampleRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_example), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.Example( - name='name_value', - )) - response = await client.get_example(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetExampleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.Example) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_example_async_from_dict(): - await test_get_example_async(request_type=dict) - - -def test_get_example_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetExampleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_example), - '__call__') as call: - call.return_value = dataset.Example() - client.get_example(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_example_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetExampleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_example), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Example()) - await client.get_example(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_example_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_example), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Example() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_example( - name='name_value', - filter='filter_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] - assert args[0].name == 'name_value' - assert args[0].filter == 'filter_value' - - -def test_get_example_flattened_error(): - client = DataLabelingServiceClient( - 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_example( - data_labeling_service.GetExampleRequest(), - name='name_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_get_example_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_example), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Example() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Example()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_example( - name='name_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_get_example_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_example( - data_labeling_service.GetExampleRequest(), - name='name_value', - filter='filter_value', - ) - - -def test_list_examples(transport: str = 'grpc', request_type=data_labeling_service.ListExamplesRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_examples), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListExamplesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_examples(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListExamplesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExamplesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_examples_from_dict(): - test_list_examples(request_type=dict) - - -def test_list_examples_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 = DataLabelingServiceClient( - 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_examples), - '__call__') as call: - client.list_examples() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListExamplesRequest() - - -@pytest.mark.asyncio -async def test_list_examples_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListExamplesRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_examples), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListExamplesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_examples(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListExamplesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExamplesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_examples_async_from_dict(): - await test_list_examples_async(request_type=dict) - - -def test_list_examples_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListExamplesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__') as call: - call.return_value = data_labeling_service.ListExamplesResponse() - client.list_examples(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_examples_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListExamplesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListExamplesResponse()) - await client.list_examples(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_examples_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListExamplesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_examples( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_examples_flattened_error(): - client = DataLabelingServiceClient( - 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_examples( - data_labeling_service.ListExamplesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_examples_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListExamplesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListExamplesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_examples( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_examples_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_examples( - data_labeling_service.ListExamplesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_examples_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - dataset.Example(), - ], - next_page_token='abc', - ), - data_labeling_service.ListExamplesResponse( - examples=[], - next_page_token='def', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_examples(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, dataset.Example) - for i in results) - -def test_list_examples_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - dataset.Example(), - ], - next_page_token='abc', - ), - data_labeling_service.ListExamplesResponse( - examples=[], - next_page_token='def', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - ], - ), - RuntimeError, - ) - pages = list(client.list_examples(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_examples_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - dataset.Example(), - ], - next_page_token='abc', - ), - data_labeling_service.ListExamplesResponse( - examples=[], - next_page_token='def', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_examples(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, dataset.Example) - for i in responses) - -@pytest.mark.asyncio -async def test_list_examples_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_examples), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - dataset.Example(), - ], - next_page_token='abc', - ), - data_labeling_service.ListExamplesResponse( - examples=[], - next_page_token='def', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListExamplesResponse( - examples=[ - dataset.Example(), - dataset.Example(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_examples(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_create_annotation_spec_set(transport: str = 'grpc', request_type=data_labeling_service.CreateAnnotationSpecSetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_annotation_spec_set.AnnotationSpecSet( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - ) - response = client.create_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateAnnotationSpecSetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_annotation_spec_set.AnnotationSpecSet) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - - -def test_create_annotation_spec_set_from_dict(): - test_create_annotation_spec_set(request_type=dict) - - -def test_create_annotation_spec_set_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 = DataLabelingServiceClient( - 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_annotation_spec_set), - '__call__') as call: - client.create_annotation_spec_set() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateAnnotationSpecSetRequest() - - -@pytest.mark.asyncio -async def test_create_annotation_spec_set_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateAnnotationSpecSetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_annotation_spec_set.AnnotationSpecSet( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - )) - response = await client.create_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateAnnotationSpecSetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_annotation_spec_set.AnnotationSpecSet) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - - -@pytest.mark.asyncio -async def test_create_annotation_spec_set_async_from_dict(): - await test_create_annotation_spec_set_async(request_type=dict) - - -def test_create_annotation_spec_set_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateAnnotationSpecSetRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_annotation_spec_set), - '__call__') as call: - call.return_value = gcd_annotation_spec_set.AnnotationSpecSet() - client.create_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_annotation_spec_set_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateAnnotationSpecSetRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_annotation_spec_set), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_annotation_spec_set.AnnotationSpecSet()) - await client.create_annotation_spec_set(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_annotation_spec_set_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_annotation_spec_set.AnnotationSpecSet() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_annotation_spec_set( - parent='parent_value', - annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(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] - assert args[0].parent == 'parent_value' - assert args[0].annotation_spec_set == gcd_annotation_spec_set.AnnotationSpecSet(name='name_value') - - -def test_create_annotation_spec_set_flattened_error(): - client = DataLabelingServiceClient( - 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_annotation_spec_set( - data_labeling_service.CreateAnnotationSpecSetRequest(), - parent='parent_value', - annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_annotation_spec_set_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_annotation_spec_set.AnnotationSpecSet() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_annotation_spec_set.AnnotationSpecSet()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_annotation_spec_set( - parent='parent_value', - annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(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] - assert args[0].parent == 'parent_value' - assert args[0].annotation_spec_set == gcd_annotation_spec_set.AnnotationSpecSet(name='name_value') - - -@pytest.mark.asyncio -async def test_create_annotation_spec_set_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_annotation_spec_set( - data_labeling_service.CreateAnnotationSpecSetRequest(), - parent='parent_value', - annotation_spec_set=gcd_annotation_spec_set.AnnotationSpecSet(name='name_value'), - ) - - -def test_get_annotation_spec_set(transport: str = 'grpc', request_type=data_labeling_service.GetAnnotationSpecSetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = annotation_spec_set.AnnotationSpecSet( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - ) - response = client.get_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetAnnotationSpecSetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, annotation_spec_set.AnnotationSpecSet) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - - -def test_get_annotation_spec_set_from_dict(): - test_get_annotation_spec_set(request_type=dict) - - -def test_get_annotation_spec_set_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 = DataLabelingServiceClient( - 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_annotation_spec_set), - '__call__') as call: - client.get_annotation_spec_set() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetAnnotationSpecSetRequest() - - -@pytest.mark.asyncio -async def test_get_annotation_spec_set_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetAnnotationSpecSetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(annotation_spec_set.AnnotationSpecSet( - name='name_value', - display_name='display_name_value', - description='description_value', - blocking_resources=['blocking_resources_value'], - )) - response = await client.get_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetAnnotationSpecSetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, annotation_spec_set.AnnotationSpecSet) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.blocking_resources == ['blocking_resources_value'] - - -@pytest.mark.asyncio -async def test_get_annotation_spec_set_async_from_dict(): - await test_get_annotation_spec_set_async(request_type=dict) - - -def test_get_annotation_spec_set_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetAnnotationSpecSetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotation_spec_set), - '__call__') as call: - call.return_value = annotation_spec_set.AnnotationSpecSet() - client.get_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_annotation_spec_set_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetAnnotationSpecSetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotation_spec_set), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(annotation_spec_set.AnnotationSpecSet()) - await client.get_annotation_spec_set(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_annotation_spec_set_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = annotation_spec_set.AnnotationSpecSet() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_annotation_spec_set( - 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] - assert args[0].name == 'name_value' - - -def test_get_annotation_spec_set_flattened_error(): - client = DataLabelingServiceClient( - 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_annotation_spec_set( - data_labeling_service.GetAnnotationSpecSetRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_annotation_spec_set_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = annotation_spec_set.AnnotationSpecSet() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(annotation_spec_set.AnnotationSpecSet()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_annotation_spec_set( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_annotation_spec_set_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_annotation_spec_set( - data_labeling_service.GetAnnotationSpecSetRequest(), - name='name_value', - ) - - -def test_list_annotation_spec_sets(transport: str = 'grpc', request_type=data_labeling_service.ListAnnotationSpecSetsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_sets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_annotation_spec_sets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListAnnotationSpecSetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnnotationSpecSetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_annotation_spec_sets_from_dict(): - test_list_annotation_spec_sets(request_type=dict) - - -def test_list_annotation_spec_sets_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 = DataLabelingServiceClient( - 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_annotation_spec_sets), - '__call__') as call: - client.list_annotation_spec_sets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListAnnotationSpecSetsRequest() - - -@pytest.mark.asyncio -async def test_list_annotation_spec_sets_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListAnnotationSpecSetsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_sets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotationSpecSetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_annotation_spec_sets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListAnnotationSpecSetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnnotationSpecSetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_annotation_spec_sets_async_from_dict(): - await test_list_annotation_spec_sets_async(request_type=dict) - - -def test_list_annotation_spec_sets_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListAnnotationSpecSetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__') as call: - call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse() - client.list_annotation_spec_sets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_annotation_spec_sets_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListAnnotationSpecSetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotationSpecSetsResponse()) - await client.list_annotation_spec_sets(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_annotation_spec_sets_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_annotation_spec_sets( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_annotation_spec_sets_flattened_error(): - client = DataLabelingServiceClient( - 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_annotation_spec_sets( - data_labeling_service.ListAnnotationSpecSetsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_annotation_spec_sets_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListAnnotationSpecSetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListAnnotationSpecSetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_annotation_spec_sets( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_annotation_spec_sets_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_annotation_spec_sets( - data_labeling_service.ListAnnotationSpecSetsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_annotation_spec_sets_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_annotation_spec_sets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, annotation_spec_set.AnnotationSpecSet) - for i in results) - -def test_list_annotation_spec_sets_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - ), - RuntimeError, - ) - pages = list(client.list_annotation_spec_sets(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_annotation_spec_sets_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_annotation_spec_sets(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, annotation_spec_set.AnnotationSpecSet) - for i in responses) - -@pytest.mark.asyncio -async def test_list_annotation_spec_sets_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_annotation_spec_sets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='abc', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[], - next_page_token='def', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListAnnotationSpecSetsResponse( - annotation_spec_sets=[ - annotation_spec_set.AnnotationSpecSet(), - annotation_spec_set.AnnotationSpecSet(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_annotation_spec_sets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_annotation_spec_set(transport: str = 'grpc', request_type=data_labeling_service.DeleteAnnotationSpecSetRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteAnnotationSpecSetRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_annotation_spec_set_from_dict(): - test_delete_annotation_spec_set(request_type=dict) - - -def test_delete_annotation_spec_set_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 = DataLabelingServiceClient( - 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_annotation_spec_set), - '__call__') as call: - client.delete_annotation_spec_set() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteAnnotationSpecSetRequest() - - -@pytest.mark.asyncio -async def test_delete_annotation_spec_set_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteAnnotationSpecSetRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteAnnotationSpecSetRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_annotation_spec_set_async_from_dict(): - await test_delete_annotation_spec_set_async(request_type=dict) - - -def test_delete_annotation_spec_set_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteAnnotationSpecSetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_annotation_spec_set), - '__call__') as call: - call.return_value = None - client.delete_annotation_spec_set(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_annotation_spec_set_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteAnnotationSpecSetRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_annotation_spec_set), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_annotation_spec_set(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_annotation_spec_set_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_annotation_spec_set( - 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] - assert args[0].name == 'name_value' - - -def test_delete_annotation_spec_set_flattened_error(): - client = DataLabelingServiceClient( - 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_annotation_spec_set( - data_labeling_service.DeleteAnnotationSpecSetRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_annotation_spec_set_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_annotation_spec_set), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_annotation_spec_set( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_annotation_spec_set_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_annotation_spec_set( - data_labeling_service.DeleteAnnotationSpecSetRequest(), - name='name_value', - ) - - -def test_create_instruction(transport: str = 'grpc', request_type=data_labeling_service.CreateInstructionRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateInstructionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_instruction_from_dict(): - test_create_instruction(request_type=dict) - - -def test_create_instruction_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 = DataLabelingServiceClient( - 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_instruction), - '__call__') as call: - client.create_instruction() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateInstructionRequest() - - -@pytest.mark.asyncio -async def test_create_instruction_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateInstructionRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instruction), - '__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.create_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateInstructionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_instruction_async_from_dict(): - await test_create_instruction_async(request_type=dict) - - -def test_create_instruction_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateInstructionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instruction), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_instruction_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateInstructionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instruction), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_instruction(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_instruction_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instruction), - '__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.create_instruction( - parent='parent_value', - instruction=gcd_instruction.Instruction(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] - assert args[0].parent == 'parent_value' - assert args[0].instruction == gcd_instruction.Instruction(name='name_value') - - -def test_create_instruction_flattened_error(): - client = DataLabelingServiceClient( - 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_instruction( - data_labeling_service.CreateInstructionRequest(), - parent='parent_value', - instruction=gcd_instruction.Instruction(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_instruction_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instruction), - '__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.create_instruction( - parent='parent_value', - instruction=gcd_instruction.Instruction(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] - assert args[0].parent == 'parent_value' - assert args[0].instruction == gcd_instruction.Instruction(name='name_value') - - -@pytest.mark.asyncio -async def test_create_instruction_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_instruction( - data_labeling_service.CreateInstructionRequest(), - parent='parent_value', - instruction=gcd_instruction.Instruction(name='name_value'), - ) - - -def test_get_instruction(transport: str = 'grpc', request_type=data_labeling_service.GetInstructionRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instruction.Instruction( - name='name_value', - display_name='display_name_value', - description='description_value', - data_type=dataset.DataType.IMAGE, - blocking_resources=['blocking_resources_value'], - ) - response = client.get_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetInstructionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, instruction.Instruction) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.data_type == dataset.DataType.IMAGE - assert response.blocking_resources == ['blocking_resources_value'] - - -def test_get_instruction_from_dict(): - test_get_instruction(request_type=dict) - - -def test_get_instruction_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 = DataLabelingServiceClient( - 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_instruction), - '__call__') as call: - client.get_instruction() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetInstructionRequest() - - -@pytest.mark.asyncio -async def test_get_instruction_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetInstructionRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instruction.Instruction( - name='name_value', - display_name='display_name_value', - description='description_value', - data_type=dataset.DataType.IMAGE, - blocking_resources=['blocking_resources_value'], - )) - response = await client.get_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetInstructionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, instruction.Instruction) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.data_type == dataset.DataType.IMAGE - assert response.blocking_resources == ['blocking_resources_value'] - - -@pytest.mark.asyncio -async def test_get_instruction_async_from_dict(): - await test_get_instruction_async(request_type=dict) - - -def test_get_instruction_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetInstructionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instruction), - '__call__') as call: - call.return_value = instruction.Instruction() - client.get_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_instruction_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetInstructionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instruction), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instruction.Instruction()) - await client.get_instruction(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_instruction_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instruction.Instruction() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_instruction( - 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] - assert args[0].name == 'name_value' - - -def test_get_instruction_flattened_error(): - client = DataLabelingServiceClient( - 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_instruction( - data_labeling_service.GetInstructionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_instruction_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instruction.Instruction() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instruction.Instruction()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_instruction( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_instruction_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_instruction( - data_labeling_service.GetInstructionRequest(), - name='name_value', - ) - - -def test_list_instructions(transport: str = 'grpc', request_type=data_labeling_service.ListInstructionsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instructions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListInstructionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_instructions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListInstructionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstructionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_instructions_from_dict(): - test_list_instructions(request_type=dict) - - -def test_list_instructions_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 = DataLabelingServiceClient( - 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_instructions), - '__call__') as call: - client.list_instructions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListInstructionsRequest() - - -@pytest.mark.asyncio -async def test_list_instructions_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListInstructionsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instructions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListInstructionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_instructions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListInstructionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstructionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_instructions_async_from_dict(): - await test_list_instructions_async(request_type=dict) - - -def test_list_instructions_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListInstructionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__') as call: - call.return_value = data_labeling_service.ListInstructionsResponse() - client.list_instructions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_instructions_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListInstructionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListInstructionsResponse()) - await client.list_instructions(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_instructions_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListInstructionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_instructions( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_instructions_flattened_error(): - client = DataLabelingServiceClient( - 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_instructions( - data_labeling_service.ListInstructionsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_instructions_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListInstructionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListInstructionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_instructions( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_instructions_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_instructions( - data_labeling_service.ListInstructionsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_instructions_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - instruction.Instruction(), - ], - next_page_token='abc', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[], - next_page_token='def', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_instructions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, instruction.Instruction) - for i in results) - -def test_list_instructions_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - instruction.Instruction(), - ], - next_page_token='abc', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[], - next_page_token='def', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - ], - ), - RuntimeError, - ) - pages = list(client.list_instructions(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_instructions_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - instruction.Instruction(), - ], - next_page_token='abc', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[], - next_page_token='def', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_instructions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, instruction.Instruction) - for i in responses) - -@pytest.mark.asyncio -async def test_list_instructions_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instructions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - instruction.Instruction(), - ], - next_page_token='abc', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[], - next_page_token='def', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListInstructionsResponse( - instructions=[ - instruction.Instruction(), - instruction.Instruction(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_instructions(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_instruction(transport: str = 'grpc', request_type=data_labeling_service.DeleteInstructionRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteInstructionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_instruction_from_dict(): - test_delete_instruction(request_type=dict) - - -def test_delete_instruction_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 = DataLabelingServiceClient( - 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_instruction), - '__call__') as call: - client.delete_instruction() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteInstructionRequest() - - -@pytest.mark.asyncio -async def test_delete_instruction_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteInstructionRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteInstructionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_instruction_async_from_dict(): - await test_delete_instruction_async(request_type=dict) - - -def test_delete_instruction_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteInstructionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instruction), - '__call__') as call: - call.return_value = None - client.delete_instruction(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_instruction_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteInstructionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instruction), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_instruction(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_instruction_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_instruction( - 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] - assert args[0].name == 'name_value' - - -def test_delete_instruction_flattened_error(): - client = DataLabelingServiceClient( - 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_instruction( - data_labeling_service.DeleteInstructionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_instruction_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instruction), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_instruction( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_instruction_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_instruction( - data_labeling_service.DeleteInstructionRequest(), - name='name_value', - ) - - -def test_get_evaluation(transport: str = 'grpc', request_type=data_labeling_service.GetEvaluationRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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', - annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, - evaluated_item_count=2129, - ) - 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] == data_labeling_service.GetEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION - assert response.evaluated_item_count == 2129 - - -def test_get_evaluation_from_dict(): - test_get_evaluation(request_type=dict) - - -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 = DataLabelingServiceClient( - 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] == data_labeling_service.GetEvaluationRequest() - - -@pytest.mark.asyncio -async def test_get_evaluation_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetEvaluationRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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', - annotation_type=annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION, - evaluated_item_count=2129, - )) - 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] == data_labeling_service.GetEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation.Evaluation) - assert response.name == 'name_value' - assert response.annotation_type == annotation.AnnotationType.IMAGE_CLASSIFICATION_ANNOTATION - assert response.evaluated_item_count == 2129 - - -@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 = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_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 = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_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 = DataLabelingServiceClient( - 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] - assert args[0].name == 'name_value' - - -def test_get_evaluation_flattened_error(): - client = DataLabelingServiceClient( - 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( - data_labeling_service.GetEvaluationRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_evaluation_flattened_async(): - client = DataLabelingServiceAsyncClient( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_evaluation_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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( - data_labeling_service.GetEvaluationRequest(), - name='name_value', - ) - - -def test_search_evaluations(transport: str = 'grpc', request_type=data_labeling_service.SearchEvaluationsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.SearchEvaluationsResponse( - next_page_token='next_page_token_value', - ) - response = client.search_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] == data_labeling_service.SearchEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchEvaluationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_evaluations_from_dict(): - test_search_evaluations(request_type=dict) - - -def test_search_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 = DataLabelingServiceClient( - 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.search_evaluations), - '__call__') as call: - client.search_evaluations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.SearchEvaluationsRequest() - - -@pytest.mark.asyncio -async def test_search_evaluations_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.SearchEvaluationsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchEvaluationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.SearchEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchEvaluationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_evaluations_async_from_dict(): - await test_search_evaluations_async(request_type=dict) - - -def test_search_evaluations_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.SearchEvaluationsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - call.return_value = data_labeling_service.SearchEvaluationsResponse() - client.search_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_search_evaluations_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.SearchEvaluationsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchEvaluationsResponse()) - await client.search_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_search_evaluations_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.SearchEvaluationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_evaluations( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_search_evaluations_flattened_error(): - client = DataLabelingServiceClient( - 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.search_evaluations( - data_labeling_service.SearchEvaluationsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_search_evaluations_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.SearchEvaluationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchEvaluationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_evaluations( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_search_evaluations_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.search_evaluations( - data_labeling_service.SearchEvaluationsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_search_evaluations_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.search_evaluations(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in results) - -def test_search_evaluations_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - pages = list(client.search_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_search_evaluations_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_evaluations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, evaluation.Evaluation) - for i in responses) - -@pytest.mark.asyncio -async def test_search_evaluations_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[], - next_page_token='def', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchEvaluationsResponse( - evaluations=[ - evaluation.Evaluation(), - evaluation.Evaluation(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_evaluations(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_search_example_comparisons(transport: str = 'grpc', request_type=data_labeling_service.SearchExampleComparisonsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.SearchExampleComparisonsResponse( - next_page_token='next_page_token_value', - ) - response = client.search_example_comparisons(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.SearchExampleComparisonsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchExampleComparisonsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_example_comparisons_from_dict(): - test_search_example_comparisons(request_type=dict) - - -def test_search_example_comparisons_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 = DataLabelingServiceClient( - 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.search_example_comparisons), - '__call__') as call: - client.search_example_comparisons() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.SearchExampleComparisonsRequest() - - -@pytest.mark.asyncio -async def test_search_example_comparisons_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.SearchExampleComparisonsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchExampleComparisonsResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_example_comparisons(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.SearchExampleComparisonsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchExampleComparisonsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_example_comparisons_async_from_dict(): - await test_search_example_comparisons_async(request_type=dict) - - -def test_search_example_comparisons_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.SearchExampleComparisonsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - call.return_value = data_labeling_service.SearchExampleComparisonsResponse() - client.search_example_comparisons(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_search_example_comparisons_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.SearchExampleComparisonsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchExampleComparisonsResponse()) - await client.search_example_comparisons(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_search_example_comparisons_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.SearchExampleComparisonsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_example_comparisons( - 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] - assert args[0].parent == 'parent_value' - - -def test_search_example_comparisons_flattened_error(): - client = DataLabelingServiceClient( - 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.search_example_comparisons( - data_labeling_service.SearchExampleComparisonsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_search_example_comparisons_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.SearchExampleComparisonsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.SearchExampleComparisonsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_example_comparisons( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_search_example_comparisons_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.search_example_comparisons( - data_labeling_service.SearchExampleComparisonsRequest(), - parent='parent_value', - ) - - -def test_search_example_comparisons_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[], - next_page_token='def', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.search_example_comparisons(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison) - for i in results) - -def test_search_example_comparisons_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[], - next_page_token='def', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - ), - RuntimeError, - ) - pages = list(client.search_example_comparisons(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_search_example_comparisons_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[], - next_page_token='def', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_example_comparisons(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison) - for i in responses) - -@pytest.mark.asyncio -async def test_search_example_comparisons_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_example_comparisons), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='abc', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[], - next_page_token='def', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - next_page_token='ghi', - ), - data_labeling_service.SearchExampleComparisonsResponse( - example_comparisons=[ - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - data_labeling_service.SearchExampleComparisonsResponse.ExampleComparison(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_example_comparisons(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_create_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.CreateEvaluationJobRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation_job.EvaluationJob( - name='name_value', - description='description_value', - state=evaluation_job.EvaluationJob.State.SCHEDULED, - schedule='schedule_value', - model_version='model_version_value', - annotation_spec_set='annotation_spec_set_value', - label_missing_ground_truth=True, - ) - response = client.create_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation_job.EvaluationJob) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED - assert response.schedule == 'schedule_value' - assert response.model_version == 'model_version_value' - assert response.annotation_spec_set == 'annotation_spec_set_value' - assert response.label_missing_ground_truth is True - - -def test_create_evaluation_job_from_dict(): - test_create_evaluation_job(request_type=dict) - - -def test_create_evaluation_job_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 = DataLabelingServiceClient( - 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_evaluation_job), - '__call__') as call: - client.create_evaluation_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateEvaluationJobRequest() - - -@pytest.mark.asyncio -async def test_create_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.CreateEvaluationJobRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob( - name='name_value', - description='description_value', - state=evaluation_job.EvaluationJob.State.SCHEDULED, - schedule='schedule_value', - model_version='model_version_value', - annotation_spec_set='annotation_spec_set_value', - label_missing_ground_truth=True, - )) - response = await client.create_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.CreateEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation_job.EvaluationJob) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED - assert response.schedule == 'schedule_value' - assert response.model_version == 'model_version_value' - assert response.annotation_spec_set == 'annotation_spec_set_value' - assert response.label_missing_ground_truth is True - - -@pytest.mark.asyncio -async def test_create_evaluation_job_async_from_dict(): - await test_create_evaluation_job_async(request_type=dict) - - -def test_create_evaluation_job_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateEvaluationJobRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_evaluation_job), - '__call__') as call: - call.return_value = evaluation_job.EvaluationJob() - client.create_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_evaluation_job_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.CreateEvaluationJobRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_evaluation_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) - await client.create_evaluation_job(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_evaluation_job_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation_job.EvaluationJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_evaluation_job( - parent='parent_value', - job=evaluation_job.EvaluationJob(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] - assert args[0].parent == 'parent_value' - assert args[0].job == evaluation_job.EvaluationJob(name='name_value') - - -def test_create_evaluation_job_flattened_error(): - client = DataLabelingServiceClient( - 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_evaluation_job( - data_labeling_service.CreateEvaluationJobRequest(), - parent='parent_value', - job=evaluation_job.EvaluationJob(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_evaluation_job_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation_job.EvaluationJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_evaluation_job( - parent='parent_value', - job=evaluation_job.EvaluationJob(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] - assert args[0].parent == 'parent_value' - assert args[0].job == evaluation_job.EvaluationJob(name='name_value') - - -@pytest.mark.asyncio -async def test_create_evaluation_job_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_evaluation_job( - data_labeling_service.CreateEvaluationJobRequest(), - parent='parent_value', - job=evaluation_job.EvaluationJob(name='name_value'), - ) - - -def test_update_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.UpdateEvaluationJobRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_evaluation_job.EvaluationJob( - name='name_value', - description='description_value', - state=gcd_evaluation_job.EvaluationJob.State.SCHEDULED, - schedule='schedule_value', - model_version='model_version_value', - annotation_spec_set='annotation_spec_set_value', - label_missing_ground_truth=True, - ) - response = client.update_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.UpdateEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_evaluation_job.EvaluationJob) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == gcd_evaluation_job.EvaluationJob.State.SCHEDULED - assert response.schedule == 'schedule_value' - assert response.model_version == 'model_version_value' - assert response.annotation_spec_set == 'annotation_spec_set_value' - assert response.label_missing_ground_truth is True - - -def test_update_evaluation_job_from_dict(): - test_update_evaluation_job(request_type=dict) - - -def test_update_evaluation_job_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 = DataLabelingServiceClient( - 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_evaluation_job), - '__call__') as call: - client.update_evaluation_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.UpdateEvaluationJobRequest() - - -@pytest.mark.asyncio -async def test_update_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.UpdateEvaluationJobRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_evaluation_job.EvaluationJob( - name='name_value', - description='description_value', - state=gcd_evaluation_job.EvaluationJob.State.SCHEDULED, - schedule='schedule_value', - model_version='model_version_value', - annotation_spec_set='annotation_spec_set_value', - label_missing_ground_truth=True, - )) - response = await client.update_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.UpdateEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_evaluation_job.EvaluationJob) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == gcd_evaluation_job.EvaluationJob.State.SCHEDULED - assert response.schedule == 'schedule_value' - assert response.model_version == 'model_version_value' - assert response.annotation_spec_set == 'annotation_spec_set_value' - assert response.label_missing_ground_truth is True - - -@pytest.mark.asyncio -async def test_update_evaluation_job_async_from_dict(): - await test_update_evaluation_job_async(request_type=dict) - - -def test_update_evaluation_job_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.UpdateEvaluationJobRequest() - - request.evaluation_job.name = 'evaluation_job.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_evaluation_job), - '__call__') as call: - call.return_value = gcd_evaluation_job.EvaluationJob() - client.update_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'evaluation_job.name=evaluation_job.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_evaluation_job_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.UpdateEvaluationJobRequest() - - request.evaluation_job.name = 'evaluation_job.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_evaluation_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_evaluation_job.EvaluationJob()) - await client.update_evaluation_job(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', - 'evaluation_job.name=evaluation_job.name/value', - ) in kw['metadata'] - - -def test_update_evaluation_job_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_evaluation_job.EvaluationJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_evaluation_job( - evaluation_job=gcd_evaluation_job.EvaluationJob(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] - assert args[0].evaluation_job == gcd_evaluation_job.EvaluationJob(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_evaluation_job_flattened_error(): - client = DataLabelingServiceClient( - 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_evaluation_job( - data_labeling_service.UpdateEvaluationJobRequest(), - evaluation_job=gcd_evaluation_job.EvaluationJob(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_evaluation_job_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_evaluation_job.EvaluationJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_evaluation_job.EvaluationJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_evaluation_job( - evaluation_job=gcd_evaluation_job.EvaluationJob(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] - assert args[0].evaluation_job == gcd_evaluation_job.EvaluationJob(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_evaluation_job_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_evaluation_job( - data_labeling_service.UpdateEvaluationJobRequest(), - evaluation_job=gcd_evaluation_job.EvaluationJob(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.GetEvaluationJobRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation_job.EvaluationJob( - name='name_value', - description='description_value', - state=evaluation_job.EvaluationJob.State.SCHEDULED, - schedule='schedule_value', - model_version='model_version_value', - annotation_spec_set='annotation_spec_set_value', - label_missing_ground_truth=True, - ) - response = client.get_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation_job.EvaluationJob) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED - assert response.schedule == 'schedule_value' - assert response.model_version == 'model_version_value' - assert response.annotation_spec_set == 'annotation_spec_set_value' - assert response.label_missing_ground_truth is True - - -def test_get_evaluation_job_from_dict(): - test_get_evaluation_job(request_type=dict) - - -def test_get_evaluation_job_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 = DataLabelingServiceClient( - 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_job), - '__call__') as call: - client.get_evaluation_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetEvaluationJobRequest() - - -@pytest.mark.asyncio -async def test_get_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.GetEvaluationJobRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob( - name='name_value', - description='description_value', - state=evaluation_job.EvaluationJob.State.SCHEDULED, - schedule='schedule_value', - model_version='model_version_value', - annotation_spec_set='annotation_spec_set_value', - label_missing_ground_truth=True, - )) - response = await client.get_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.GetEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, evaluation_job.EvaluationJob) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == evaluation_job.EvaluationJob.State.SCHEDULED - assert response.schedule == 'schedule_value' - assert response.model_version == 'model_version_value' - assert response.annotation_spec_set == 'annotation_spec_set_value' - assert response.label_missing_ground_truth is True - - -@pytest.mark.asyncio -async def test_get_evaluation_job_async_from_dict(): - await test_get_evaluation_job_async(request_type=dict) - - -def test_get_evaluation_job_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetEvaluationJobRequest() - - 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_job), - '__call__') as call: - call.return_value = evaluation_job.EvaluationJob() - client.get_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_job_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.GetEvaluationJobRequest() - - 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_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) - await client.get_evaluation_job(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_job_flattened(): - client = DataLabelingServiceClient( - 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_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation_job.EvaluationJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -def test_get_evaluation_job_flattened_error(): - client = DataLabelingServiceClient( - 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_job( - data_labeling_service.GetEvaluationJobRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_evaluation_job_flattened_async(): - client = DataLabelingServiceAsyncClient( - 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_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = evaluation_job.EvaluationJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(evaluation_job.EvaluationJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_evaluation_job_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_job( - data_labeling_service.GetEvaluationJobRequest(), - name='name_value', - ) - - -def test_pause_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.PauseEvaluationJobRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.pause_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.PauseEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_pause_evaluation_job_from_dict(): - test_pause_evaluation_job(request_type=dict) - - -def test_pause_evaluation_job_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 = DataLabelingServiceClient( - 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.pause_evaluation_job), - '__call__') as call: - client.pause_evaluation_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.PauseEvaluationJobRequest() - - -@pytest.mark.asyncio -async def test_pause_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.PauseEvaluationJobRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.pause_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.PauseEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_pause_evaluation_job_async_from_dict(): - await test_pause_evaluation_job_async(request_type=dict) - - -def test_pause_evaluation_job_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.PauseEvaluationJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_evaluation_job), - '__call__') as call: - call.return_value = None - client.pause_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_pause_evaluation_job_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.PauseEvaluationJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_evaluation_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.pause_evaluation_job(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_pause_evaluation_job_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.pause_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -def test_pause_evaluation_job_flattened_error(): - client = DataLabelingServiceClient( - 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.pause_evaluation_job( - data_labeling_service.PauseEvaluationJobRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_pause_evaluation_job_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.pause_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_pause_evaluation_job_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.pause_evaluation_job( - data_labeling_service.PauseEvaluationJobRequest(), - name='name_value', - ) - - -def test_resume_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.ResumeEvaluationJobRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.resume_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ResumeEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_resume_evaluation_job_from_dict(): - test_resume_evaluation_job(request_type=dict) - - -def test_resume_evaluation_job_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 = DataLabelingServiceClient( - 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.resume_evaluation_job), - '__call__') as call: - client.resume_evaluation_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ResumeEvaluationJobRequest() - - -@pytest.mark.asyncio -async def test_resume_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ResumeEvaluationJobRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.resume_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ResumeEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_resume_evaluation_job_async_from_dict(): - await test_resume_evaluation_job_async(request_type=dict) - - -def test_resume_evaluation_job_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ResumeEvaluationJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_evaluation_job), - '__call__') as call: - call.return_value = None - client.resume_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_resume_evaluation_job_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ResumeEvaluationJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_evaluation_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.resume_evaluation_job(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_resume_evaluation_job_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.resume_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -def test_resume_evaluation_job_flattened_error(): - client = DataLabelingServiceClient( - 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.resume_evaluation_job( - data_labeling_service.ResumeEvaluationJobRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_resume_evaluation_job_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.resume_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_resume_evaluation_job_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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.resume_evaluation_job( - data_labeling_service.ResumeEvaluationJobRequest(), - name='name_value', - ) - - -def test_delete_evaluation_job(transport: str = 'grpc', request_type=data_labeling_service.DeleteEvaluationJobRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_evaluation_job_from_dict(): - test_delete_evaluation_job(request_type=dict) - - -def test_delete_evaluation_job_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 = DataLabelingServiceClient( - 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_evaluation_job), - '__call__') as call: - client.delete_evaluation_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteEvaluationJobRequest() - - -@pytest.mark.asyncio -async def test_delete_evaluation_job_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.DeleteEvaluationJobRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.DeleteEvaluationJobRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_evaluation_job_async_from_dict(): - await test_delete_evaluation_job_async(request_type=dict) - - -def test_delete_evaluation_job_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteEvaluationJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_evaluation_job), - '__call__') as call: - call.return_value = None - client.delete_evaluation_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_evaluation_job_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.DeleteEvaluationJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_evaluation_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_evaluation_job(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_evaluation_job_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -def test_delete_evaluation_job_flattened_error(): - client = DataLabelingServiceClient( - 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_evaluation_job( - data_labeling_service.DeleteEvaluationJobRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_evaluation_job_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_evaluation_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_evaluation_job( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_evaluation_job_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_evaluation_job( - data_labeling_service.DeleteEvaluationJobRequest(), - name='name_value', - ) - - -def test_list_evaluation_jobs(transport: str = 'grpc', request_type=data_labeling_service.ListEvaluationJobsRequest): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListEvaluationJobsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_evaluation_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListEvaluationJobsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationJobsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_evaluation_jobs_from_dict(): - test_list_evaluation_jobs(request_type=dict) - - -def test_list_evaluation_jobs_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 = DataLabelingServiceClient( - 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_evaluation_jobs), - '__call__') as call: - client.list_evaluation_jobs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListEvaluationJobsRequest() - - -@pytest.mark.asyncio -async def test_list_evaluation_jobs_async(transport: str = 'grpc_asyncio', request_type=data_labeling_service.ListEvaluationJobsRequest): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_evaluation_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListEvaluationJobsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_evaluation_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == data_labeling_service.ListEvaluationJobsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEvaluationJobsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_evaluation_jobs_async_from_dict(): - await test_list_evaluation_jobs_async(request_type=dict) - - -def test_list_evaluation_jobs_field_headers(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListEvaluationJobsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__') as call: - call.return_value = data_labeling_service.ListEvaluationJobsResponse() - client.list_evaluation_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_evaluation_jobs_field_headers_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = data_labeling_service.ListEvaluationJobsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListEvaluationJobsResponse()) - await client.list_evaluation_jobs(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_evaluation_jobs_flattened(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListEvaluationJobsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_evaluation_jobs( - parent='parent_value', - filter='filter_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] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_evaluation_jobs_flattened_error(): - client = DataLabelingServiceClient( - 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_evaluation_jobs( - data_labeling_service.ListEvaluationJobsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_evaluation_jobs_flattened_async(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = data_labeling_service.ListEvaluationJobsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_labeling_service.ListEvaluationJobsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_evaluation_jobs( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_evaluation_jobs_flattened_error_async(): - client = DataLabelingServiceAsyncClient( - 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_evaluation_jobs( - data_labeling_service.ListEvaluationJobsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_evaluation_jobs_pager(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - next_page_token='abc', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[], - next_page_token='def', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_evaluation_jobs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, evaluation_job.EvaluationJob) - for i in results) - -def test_list_evaluation_jobs_pages(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - next_page_token='abc', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[], - next_page_token='def', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - ), - RuntimeError, - ) - pages = list(client.list_evaluation_jobs(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_evaluation_jobs_async_pager(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - next_page_token='abc', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[], - next_page_token='def', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_evaluation_jobs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, evaluation_job.EvaluationJob) - for i in responses) - -@pytest.mark.asyncio -async def test_list_evaluation_jobs_async_pages(): - client = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_evaluation_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - next_page_token='abc', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[], - next_page_token='def', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - ], - next_page_token='ghi', - ), - data_labeling_service.ListEvaluationJobsResponse( - evaluation_jobs=[ - evaluation_job.EvaluationJob(), - evaluation_job.EvaluationJob(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_evaluation_jobs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DataLabelingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DataLabelingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataLabelingServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DataLabelingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataLabelingServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataLabelingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DataLabelingServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataLabelingServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DataLabelingServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DataLabelingServiceGrpcTransport, - transports.DataLabelingServiceGrpcAsyncIOTransport, -]) -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() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DataLabelingServiceGrpcTransport, - ) - -def test_data_labeling_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DataLabelingServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_data_labeling_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DataLabelingServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_dataset', - 'get_dataset', - 'list_datasets', - 'delete_dataset', - 'import_data', - 'export_data', - 'get_data_item', - 'list_data_items', - 'get_annotated_dataset', - 'list_annotated_datasets', - 'delete_annotated_dataset', - 'label_image', - 'label_video', - 'label_text', - 'get_example', - 'list_examples', - 'create_annotation_spec_set', - 'get_annotation_spec_set', - 'list_annotation_spec_sets', - 'delete_annotation_spec_set', - 'create_instruction', - 'get_instruction', - 'list_instructions', - 'delete_instruction', - 'get_evaluation', - 'search_evaluations', - 'search_example_comparisons', - 'create_evaluation_job', - 'update_evaluation_job', - 'get_evaluation_job', - 'pause_evaluation_job', - 'resume_evaluation_job', - 'delete_evaluation_job', - 'list_evaluation_jobs', - ) - 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 - - -@requires_google_auth_gte_1_25_0 -def test_data_labeling_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.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataLabelingServiceTransport( - 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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_data_labeling_service_base_transport_with_credentials_file_old_google_auth(): - # 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.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataLabelingServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_data_labeling_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.datalabeling_v1beta1.services.data_labeling_service.transports.DataLabelingServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataLabelingServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_data_labeling_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) - DataLabelingServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_data_labeling_service_auth_adc_old_google_auth(): - # 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) - DataLabelingServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DataLabelingServiceGrpcTransport, - transports.DataLabelingServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_data_labeling_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.DataLabelingServiceGrpcTransport, - transports.DataLabelingServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_data_labeling_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DataLabelingServiceGrpcTransport, grpc_helpers), - (transports.DataLabelingServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_data_labeling_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( - "datalabeling.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="datalabeling.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DataLabelingServiceGrpcTransport, transports.DataLabelingServiceGrpcAsyncIOTransport]) -def test_data_labeling_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_data_labeling_service_host_no_port(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datalabeling.googleapis.com'), - ) - assert client.transport._host == 'datalabeling.googleapis.com:443' - - -def test_data_labeling_service_host_with_port(): - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datalabeling.googleapis.com:8000'), - ) - assert client.transport._host == 'datalabeling.googleapis.com:8000' - -def test_data_labeling_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataLabelingServiceGrpcTransport( - 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_data_labeling_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataLabelingServiceGrpcAsyncIOTransport( - 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.DataLabelingServiceGrpcTransport, transports.DataLabelingServiceGrpcAsyncIOTransport]) -def test_data_labeling_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.DataLabelingServiceGrpcTransport, transports.DataLabelingServiceGrpcAsyncIOTransport]) -def test_data_labeling_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_data_labeling_service_grpc_lro_client(): - client = DataLabelingServiceClient( - 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_data_labeling_service_grpc_lro_async_client(): - client = DataLabelingServiceAsyncClient( - 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_annotated_dataset_path(): - project = "squid" - dataset = "clam" - annotated_dataset = "whelk" - expected = "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, ) - actual = DataLabelingServiceClient.annotated_dataset_path(project, dataset, annotated_dataset) - assert expected == actual - - -def test_parse_annotated_dataset_path(): - expected = { - "project": "octopus", - "dataset": "oyster", - "annotated_dataset": "nudibranch", - } - path = DataLabelingServiceClient.annotated_dataset_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_annotated_dataset_path(path) - assert expected == actual - -def test_annotation_spec_set_path(): - project = "cuttlefish" - annotation_spec_set = "mussel" - expected = "projects/{project}/annotationSpecSets/{annotation_spec_set}".format(project=project, annotation_spec_set=annotation_spec_set, ) - actual = DataLabelingServiceClient.annotation_spec_set_path(project, annotation_spec_set) - assert expected == actual - - -def test_parse_annotation_spec_set_path(): - expected = { - "project": "winkle", - "annotation_spec_set": "nautilus", - } - path = DataLabelingServiceClient.annotation_spec_set_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_annotation_spec_set_path(path) - assert expected == actual - -def test_data_item_path(): - project = "scallop" - dataset = "abalone" - data_item = "squid" - expected = "projects/{project}/datasets/{dataset}/dataItems/{data_item}".format(project=project, dataset=dataset, data_item=data_item, ) - actual = DataLabelingServiceClient.data_item_path(project, dataset, data_item) - assert expected == actual - - -def test_parse_data_item_path(): - expected = { - "project": "clam", - "dataset": "whelk", - "data_item": "octopus", - } - path = DataLabelingServiceClient.data_item_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_data_item_path(path) - assert expected == actual - -def test_dataset_path(): - project = "oyster" - dataset = "nudibranch" - expected = "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) - actual = DataLabelingServiceClient.dataset_path(project, dataset) - assert expected == actual - - -def test_parse_dataset_path(): - expected = { - "project": "cuttlefish", - "dataset": "mussel", - } - path = DataLabelingServiceClient.dataset_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_dataset_path(path) - assert expected == actual - -def test_evaluation_path(): - project = "winkle" - dataset = "nautilus" - evaluation = "scallop" - expected = "projects/{project}/datasets/{dataset}/evaluations/{evaluation}".format(project=project, dataset=dataset, evaluation=evaluation, ) - actual = DataLabelingServiceClient.evaluation_path(project, dataset, evaluation) - assert expected == actual - - -def test_parse_evaluation_path(): - expected = { - "project": "abalone", - "dataset": "squid", - "evaluation": "clam", - } - path = DataLabelingServiceClient.evaluation_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_evaluation_path(path) - assert expected == actual - -def test_evaluation_job_path(): - project = "whelk" - evaluation_job = "octopus" - expected = "projects/{project}/evaluationJobs/{evaluation_job}".format(project=project, evaluation_job=evaluation_job, ) - actual = DataLabelingServiceClient.evaluation_job_path(project, evaluation_job) - assert expected == actual - - -def test_parse_evaluation_job_path(): - expected = { - "project": "oyster", - "evaluation_job": "nudibranch", - } - path = DataLabelingServiceClient.evaluation_job_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_evaluation_job_path(path) - assert expected == actual - -def test_example_path(): - project = "cuttlefish" - dataset = "mussel" - annotated_dataset = "winkle" - example = "nautilus" - expected = "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}".format(project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, ) - actual = DataLabelingServiceClient.example_path(project, dataset, annotated_dataset, example) - assert expected == actual - - -def test_parse_example_path(): - expected = { - "project": "scallop", - "dataset": "abalone", - "annotated_dataset": "squid", - "example": "clam", - } - path = DataLabelingServiceClient.example_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_example_path(path) - assert expected == actual - -def test_instruction_path(): - project = "whelk" - instruction = "octopus" - expected = "projects/{project}/instructions/{instruction}".format(project=project, instruction=instruction, ) - actual = DataLabelingServiceClient.instruction_path(project, instruction) - assert expected == actual - - -def test_parse_instruction_path(): - expected = { - "project": "oyster", - "instruction": "nudibranch", - } - path = DataLabelingServiceClient.instruction_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_instruction_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DataLabelingServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = DataLabelingServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = DataLabelingServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = DataLabelingServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DataLabelingServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = DataLabelingServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = DataLabelingServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = DataLabelingServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.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 = DataLabelingServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = DataLabelingServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DataLabelingServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DataLabelingServiceTransport, '_prep_wrapped_messages') as prep: - client = DataLabelingServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DataLabelingServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DataLabelingServiceClient.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 = DataLabelingServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DataLabelingServiceClient( - 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 = DataLabelingServiceClient( - 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() diff --git a/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py b/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py index 78027b2..a4d2fe6 100644 --- a/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py +++ b/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async 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.datalabeling_v1beta1.services.data_labeling_service import ( @@ -9970,6 +9971,9 @@ def test_data_labeling_service_base_transport(): 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): @@ -10656,3 +10660,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): 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 = DataLabelingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataLabelingServiceClient( + 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 = DataLabelingServiceClient( + 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()