- On January 1, 2020 this library will no longer support Python 2 on the latest released version. - Previously released library versions will continue to be available. For more information please + As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.
{% block body %} {% endblock %} diff --git a/docs/automl_v1/services.rst b/docs/automl_v1/services.rst new file mode 100644 index 00000000..b57ca45e --- /dev/null +++ b/docs/automl_v1/services.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Automl v1 API +======================================= + +.. automodule:: google.cloud.automl_v1.services.auto_ml + :members: + :inherited-members: +.. automodule:: google.cloud.automl_v1.services.prediction_service + :members: + :inherited-members: diff --git a/docs/automl_v1/types.rst b/docs/automl_v1/types.rst new file mode 100644 index 00000000..47a76a80 --- /dev/null +++ b/docs/automl_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Automl v1 API +==================================== + +.. automodule:: google.cloud.automl_v1.types + :members: diff --git a/docs/automl_v1beta1/services.rst b/docs/automl_v1beta1/services.rst new file mode 100644 index 00000000..787e8566 --- /dev/null +++ b/docs/automl_v1beta1/services.rst @@ -0,0 +1,12 @@ +Services for Google Cloud Automl v1beta1 API +============================================ + +.. automodule:: google.cloud.automl_v1beta1.services.auto_ml + :members: + :inherited-members: +.. automodule:: google.cloud.automl_v1beta1.services.prediction_service + :members: + :inherited-members: +.. automodule:: google.cloud.automl_v1beta1.services.tables + :members: + :inherited-members: diff --git a/docs/automl_v1beta1/types.rst b/docs/automl_v1beta1/types.rst new file mode 100644 index 00000000..bf190b5b --- /dev/null +++ b/docs/automl_v1beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Automl v1beta1 API +========================================= + +.. automodule:: google.cloud.automl_v1beta1.types + :members: diff --git a/docs/conf.py b/docs/conf.py index 0b6aebeb..fcaca368 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,6 +20,10 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ @@ -38,21 +42,18 @@ "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", + "recommonmark", ] # autodoc/autosummary flags autoclass_content = "both" -autodoc_default_flags = ["members"] +autodoc_default_options = {"members": True} 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'] @@ -93,7 +94,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -340,7 +346,7 @@ intersphinx_mapping = { "python": ("http://python.readthedocs.org/en/latest/", None), "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.io/grpc/python/", None), } diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index 757fc1a0..00000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud AutoML API -=========================== - -.. automodule:: google.cloud.automl_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index 5fd25134..00000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud AutoML API Client -================================= - -.. automodule:: google.cloud.automl_v1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst deleted file mode 100644 index 268baa5b..00000000 --- a/docs/gapic/v1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud AutoML API -=========================== - -.. automodule:: google.cloud.automl_v1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/tables.rst b/docs/gapic/v1beta1/tables.rst deleted file mode 100644 index 54ed6a20..00000000 --- a/docs/gapic/v1beta1/tables.rst +++ /dev/null @@ -1,5 +0,0 @@ -A tables-specific client for AutoML -=================================== - -.. automodule:: google.cloud.automl_v1beta1.tables.tables_client - :members: diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst deleted file mode 100644 index 27ce6644..00000000 --- a/docs/gapic/v1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud AutoML API Client -================================= - -.. automodule:: google.cloud.automl_v1beta1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 90c2bfd5..05219311 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,5 +1,7 @@ .. include:: README.rst +.. include:: multiprocessing.rst + This package includes clients for multiple versions of the Cloud AutoML API. By default, you will get ``v1``, the latest stable version. @@ -8,8 +10,8 @@ v1 API Reference .. toctree:: :maxdepth: 2 - gapic/v1/api - gapic/v1/types + automl_v1/services + automl_v1/types Previous beta release v1beta1 is provided as well. @@ -20,9 +22,19 @@ v1beta1 API Reference .. toctree:: :maxdepth: 2 - gapic/v1beta1/api - gapic/v1beta1/types - gapic/v1beta1/tables + automl_v1beta1/services + automl_v1beta1/types + + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING @@ -35,3 +47,5 @@ For a list of all ``google-cloud-automl`` releases: :maxdepth: 2 changelog + + diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst new file mode 100644 index 00000000..1cb29d4c --- /dev/null +++ b/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpcio` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.Pool` or + :class:`multiprocessing.Process`. diff --git a/google/cloud/automl/__init__.py b/google/cloud/automl/__init__.py new file mode 100644 index 00000000..e6e6a762 --- /dev/null +++ b/google/cloud/automl/__init__.py @@ -0,0 +1,200 @@ +# -*- 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.automl_v1.services.auto_ml.async_client import AutoMlAsyncClient +from google.cloud.automl_v1.services.auto_ml.client import AutoMlClient +from google.cloud.automl_v1.services.prediction_service.async_client import ( + PredictionServiceAsyncClient, +) +from google.cloud.automl_v1.services.prediction_service.client import ( + PredictionServiceClient, +) +from google.cloud.automl_v1.types.annotation_payload import AnnotationPayload +from google.cloud.automl_v1.types.annotation_spec import AnnotationSpec +from google.cloud.automl_v1.types.classification import ClassificationAnnotation +from google.cloud.automl_v1.types.classification import ClassificationEvaluationMetrics +from google.cloud.automl_v1.types.classification import ClassificationType +from google.cloud.automl_v1.types.data_items import Document +from google.cloud.automl_v1.types.data_items import DocumentDimensions +from google.cloud.automl_v1.types.data_items import ExamplePayload +from google.cloud.automl_v1.types.data_items import Image +from google.cloud.automl_v1.types.data_items import TextSnippet +from google.cloud.automl_v1.types.dataset import Dataset +from google.cloud.automl_v1.types.detection import BoundingBoxMetricsEntry +from google.cloud.automl_v1.types.detection import ImageObjectDetectionAnnotation +from google.cloud.automl_v1.types.detection import ImageObjectDetectionEvaluationMetrics +from google.cloud.automl_v1.types.geometry import BoundingPoly +from google.cloud.automl_v1.types.geometry import NormalizedVertex +from google.cloud.automl_v1.types.image import ImageClassificationDatasetMetadata +from google.cloud.automl_v1.types.image import ( + ImageClassificationModelDeploymentMetadata, +) +from google.cloud.automl_v1.types.image import ImageClassificationModelMetadata +from google.cloud.automl_v1.types.image import ImageObjectDetectionDatasetMetadata +from google.cloud.automl_v1.types.image import ( + ImageObjectDetectionModelDeploymentMetadata, +) +from google.cloud.automl_v1.types.image import ImageObjectDetectionModelMetadata +from google.cloud.automl_v1.types.io import BatchPredictInputConfig +from google.cloud.automl_v1.types.io import BatchPredictOutputConfig +from google.cloud.automl_v1.types.io import DocumentInputConfig +from google.cloud.automl_v1.types.io import GcsDestination +from google.cloud.automl_v1.types.io import GcsSource +from google.cloud.automl_v1.types.io import InputConfig +from google.cloud.automl_v1.types.io import ModelExportOutputConfig +from google.cloud.automl_v1.types.io import OutputConfig +from google.cloud.automl_v1.types.model import Model +from google.cloud.automl_v1.types.model_evaluation import ModelEvaluation +from google.cloud.automl_v1.types.operations import BatchPredictOperationMetadata +from google.cloud.automl_v1.types.operations import CreateDatasetOperationMetadata +from google.cloud.automl_v1.types.operations import CreateModelOperationMetadata +from google.cloud.automl_v1.types.operations import DeleteOperationMetadata +from google.cloud.automl_v1.types.operations import DeployModelOperationMetadata +from google.cloud.automl_v1.types.operations import ExportDataOperationMetadata +from google.cloud.automl_v1.types.operations import ExportModelOperationMetadata +from google.cloud.automl_v1.types.operations import ImportDataOperationMetadata +from google.cloud.automl_v1.types.operations import OperationMetadata +from google.cloud.automl_v1.types.operations import UndeployModelOperationMetadata +from google.cloud.automl_v1.types.prediction_service import BatchPredictRequest +from google.cloud.automl_v1.types.prediction_service import BatchPredictResult +from google.cloud.automl_v1.types.prediction_service import PredictRequest +from google.cloud.automl_v1.types.prediction_service import PredictResponse +from google.cloud.automl_v1.types.service import CreateDatasetRequest +from google.cloud.automl_v1.types.service import CreateModelRequest +from google.cloud.automl_v1.types.service import DeleteDatasetRequest +from google.cloud.automl_v1.types.service import DeleteModelRequest +from google.cloud.automl_v1.types.service import DeployModelRequest +from google.cloud.automl_v1.types.service import ExportDataRequest +from google.cloud.automl_v1.types.service import ExportModelRequest +from google.cloud.automl_v1.types.service import GetAnnotationSpecRequest +from google.cloud.automl_v1.types.service import GetDatasetRequest +from google.cloud.automl_v1.types.service import GetModelEvaluationRequest +from google.cloud.automl_v1.types.service import GetModelRequest +from google.cloud.automl_v1.types.service import ImportDataRequest +from google.cloud.automl_v1.types.service import ListDatasetsRequest +from google.cloud.automl_v1.types.service import ListDatasetsResponse +from google.cloud.automl_v1.types.service import ListModelEvaluationsRequest +from google.cloud.automl_v1.types.service import ListModelEvaluationsResponse +from google.cloud.automl_v1.types.service import ListModelsRequest +from google.cloud.automl_v1.types.service import ListModelsResponse +from google.cloud.automl_v1.types.service import UndeployModelRequest +from google.cloud.automl_v1.types.service import UpdateDatasetRequest +from google.cloud.automl_v1.types.service import UpdateModelRequest +from google.cloud.automl_v1.types.text import TextClassificationDatasetMetadata +from google.cloud.automl_v1.types.text import TextClassificationModelMetadata +from google.cloud.automl_v1.types.text import TextExtractionDatasetMetadata +from google.cloud.automl_v1.types.text import TextExtractionModelMetadata +from google.cloud.automl_v1.types.text import TextSentimentDatasetMetadata +from google.cloud.automl_v1.types.text import TextSentimentModelMetadata +from google.cloud.automl_v1.types.text_extraction import TextExtractionAnnotation +from google.cloud.automl_v1.types.text_extraction import TextExtractionEvaluationMetrics +from google.cloud.automl_v1.types.text_segment import TextSegment +from google.cloud.automl_v1.types.text_sentiment import TextSentimentAnnotation +from google.cloud.automl_v1.types.text_sentiment import TextSentimentEvaluationMetrics +from google.cloud.automl_v1.types.translation import TranslationAnnotation +from google.cloud.automl_v1.types.translation import TranslationDatasetMetadata +from google.cloud.automl_v1.types.translation import TranslationEvaluationMetrics +from google.cloud.automl_v1.types.translation import TranslationModelMetadata + +__all__ = ( + "AnnotationPayload", + "AnnotationSpec", + "AutoMlAsyncClient", + "AutoMlClient", + "BatchPredictInputConfig", + "BatchPredictOperationMetadata", + "BatchPredictOutputConfig", + "BatchPredictRequest", + "BatchPredictResult", + "BoundingBoxMetricsEntry", + "BoundingPoly", + "ClassificationAnnotation", + "ClassificationEvaluationMetrics", + "ClassificationType", + "CreateDatasetOperationMetadata", + "CreateDatasetRequest", + "CreateModelOperationMetadata", + "CreateModelRequest", + "Dataset", + "DeleteDatasetRequest", + "DeleteModelRequest", + "DeleteOperationMetadata", + "DeployModelOperationMetadata", + "DeployModelRequest", + "Document", + "DocumentDimensions", + "DocumentInputConfig", + "ExamplePayload", + "ExportDataOperationMetadata", + "ExportDataRequest", + "ExportModelOperationMetadata", + "ExportModelRequest", + "GcsDestination", + "GcsSource", + "GetAnnotationSpecRequest", + "GetDatasetRequest", + "GetModelEvaluationRequest", + "GetModelRequest", + "Image", + "ImageClassificationDatasetMetadata", + "ImageClassificationModelDeploymentMetadata", + "ImageClassificationModelMetadata", + "ImageObjectDetectionAnnotation", + "ImageObjectDetectionDatasetMetadata", + "ImageObjectDetectionEvaluationMetrics", + "ImageObjectDetectionModelDeploymentMetadata", + "ImageObjectDetectionModelMetadata", + "ImportDataOperationMetadata", + "ImportDataRequest", + "InputConfig", + "ListDatasetsRequest", + "ListDatasetsResponse", + "ListModelEvaluationsRequest", + "ListModelEvaluationsResponse", + "ListModelsRequest", + "ListModelsResponse", + "Model", + "ModelEvaluation", + "ModelExportOutputConfig", + "NormalizedVertex", + "OperationMetadata", + "OutputConfig", + "PredictRequest", + "PredictResponse", + "PredictionServiceAsyncClient", + "PredictionServiceClient", + "TextClassificationDatasetMetadata", + "TextClassificationModelMetadata", + "TextExtractionAnnotation", + "TextExtractionDatasetMetadata", + "TextExtractionEvaluationMetrics", + "TextExtractionModelMetadata", + "TextSegment", + "TextSentimentAnnotation", + "TextSentimentDatasetMetadata", + "TextSentimentEvaluationMetrics", + "TextSentimentModelMetadata", + "TextSnippet", + "TranslationAnnotation", + "TranslationDatasetMetadata", + "TranslationEvaluationMetrics", + "TranslationModelMetadata", + "UndeployModelOperationMetadata", + "UndeployModelRequest", + "UpdateDatasetRequest", + "UpdateModelRequest", +) diff --git a/google/cloud/automl/py.typed b/google/cloud/automl/py.typed new file mode 100644 index 00000000..0560ba18 --- /dev/null +++ b/google/cloud/automl/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-automl package uses inline types. diff --git a/google/cloud/automl_v1/__init__.py b/google/cloud/automl_v1/__init__.py index a663f191..b5f76f81 100644 --- a/google/cloud/automl_v1/__init__.py +++ b/google/cloud/automl_v1/__init__.py @@ -1,47 +1,189 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.automl_v1 import types -from google.cloud.automl_v1.gapic import auto_ml_client -from google.cloud.automl_v1.gapic import enums -from google.cloud.automl_v1.gapic import prediction_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7." - "More details about Python 2 support for Google Cloud Client Libraries" - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class AutoMlClient(auto_ml_client.AutoMlClient): - __doc__ = auto_ml_client.AutoMlClient.__doc__ - enums = enums - - -class PredictionServiceClient(prediction_service_client.PredictionServiceClient): - __doc__ = prediction_service_client.PredictionServiceClient.__doc__ - enums = enums +from .services.auto_ml import AutoMlClient +from .services.prediction_service import PredictionServiceClient +from .types.annotation_payload import AnnotationPayload +from .types.annotation_spec import AnnotationSpec +from .types.classification import ClassificationAnnotation +from .types.classification import ClassificationEvaluationMetrics +from .types.classification import ClassificationType +from .types.data_items import Document +from .types.data_items import DocumentDimensions +from .types.data_items import ExamplePayload +from .types.data_items import Image +from .types.data_items import TextSnippet +from .types.dataset import Dataset +from .types.detection import BoundingBoxMetricsEntry +from .types.detection import ImageObjectDetectionAnnotation +from .types.detection import ImageObjectDetectionEvaluationMetrics +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.image import ImageClassificationDatasetMetadata +from .types.image import ImageClassificationModelDeploymentMetadata +from .types.image import ImageClassificationModelMetadata +from .types.image import ImageObjectDetectionDatasetMetadata +from .types.image import ImageObjectDetectionModelDeploymentMetadata +from .types.image import ImageObjectDetectionModelMetadata +from .types.io import BatchPredictInputConfig +from .types.io import BatchPredictOutputConfig +from .types.io import DocumentInputConfig +from .types.io import GcsDestination +from .types.io import GcsSource +from .types.io import InputConfig +from .types.io import ModelExportOutputConfig +from .types.io import OutputConfig +from .types.model import Model +from .types.model_evaluation import ModelEvaluation +from .types.operations import BatchPredictOperationMetadata +from .types.operations import CreateDatasetOperationMetadata +from .types.operations import CreateModelOperationMetadata +from .types.operations import DeleteOperationMetadata +from .types.operations import DeployModelOperationMetadata +from .types.operations import ExportDataOperationMetadata +from .types.operations import ExportModelOperationMetadata +from .types.operations import ImportDataOperationMetadata +from .types.operations import OperationMetadata +from .types.operations import UndeployModelOperationMetadata +from .types.prediction_service import BatchPredictRequest +from .types.prediction_service import BatchPredictResult +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.service import CreateDatasetRequest +from .types.service import CreateModelRequest +from .types.service import DeleteDatasetRequest +from .types.service import DeleteModelRequest +from .types.service import DeployModelRequest +from .types.service import ExportDataRequest +from .types.service import ExportModelRequest +from .types.service import GetAnnotationSpecRequest +from .types.service import GetDatasetRequest +from .types.service import GetModelEvaluationRequest +from .types.service import GetModelRequest +from .types.service import ImportDataRequest +from .types.service import ListDatasetsRequest +from .types.service import ListDatasetsResponse +from .types.service import ListModelEvaluationsRequest +from .types.service import ListModelEvaluationsResponse +from .types.service import ListModelsRequest +from .types.service import ListModelsResponse +from .types.service import UndeployModelRequest +from .types.service import UpdateDatasetRequest +from .types.service import UpdateModelRequest +from .types.text import TextClassificationDatasetMetadata +from .types.text import TextClassificationModelMetadata +from .types.text import TextExtractionDatasetMetadata +from .types.text import TextExtractionModelMetadata +from .types.text import TextSentimentDatasetMetadata +from .types.text import TextSentimentModelMetadata +from .types.text_extraction import TextExtractionAnnotation +from .types.text_extraction import TextExtractionEvaluationMetrics +from .types.text_segment import TextSegment +from .types.text_sentiment import TextSentimentAnnotation +from .types.text_sentiment import TextSentimentEvaluationMetrics +from .types.translation import TranslationAnnotation +from .types.translation import TranslationDatasetMetadata +from .types.translation import TranslationEvaluationMetrics +from .types.translation import TranslationModelMetadata -__all__ = ("enums", "types", "AutoMlClient", "PredictionServiceClient") +__all__ = ( + "AnnotationPayload", + "AnnotationSpec", + "BatchPredictInputConfig", + "BatchPredictOperationMetadata", + "BatchPredictOutputConfig", + "BatchPredictRequest", + "BatchPredictResult", + "BoundingBoxMetricsEntry", + "BoundingPoly", + "ClassificationAnnotation", + "ClassificationEvaluationMetrics", + "ClassificationType", + "CreateDatasetOperationMetadata", + "CreateDatasetRequest", + "CreateModelOperationMetadata", + "CreateModelRequest", + "Dataset", + "DeleteDatasetRequest", + "DeleteModelRequest", + "DeleteOperationMetadata", + "DeployModelOperationMetadata", + "DeployModelRequest", + "Document", + "DocumentDimensions", + "DocumentInputConfig", + "ExamplePayload", + "ExportDataOperationMetadata", + "ExportDataRequest", + "ExportModelOperationMetadata", + "ExportModelRequest", + "GcsDestination", + "GcsSource", + "GetAnnotationSpecRequest", + "GetDatasetRequest", + "GetModelEvaluationRequest", + "GetModelRequest", + "Image", + "ImageClassificationDatasetMetadata", + "ImageClassificationModelDeploymentMetadata", + "ImageClassificationModelMetadata", + "ImageObjectDetectionAnnotation", + "ImageObjectDetectionDatasetMetadata", + "ImageObjectDetectionEvaluationMetrics", + "ImageObjectDetectionModelDeploymentMetadata", + "ImageObjectDetectionModelMetadata", + "ImportDataOperationMetadata", + "ImportDataRequest", + "InputConfig", + "ListDatasetsRequest", + "ListDatasetsResponse", + "ListModelEvaluationsRequest", + "ListModelEvaluationsResponse", + "ListModelsRequest", + "ListModelsResponse", + "Model", + "ModelEvaluation", + "ModelExportOutputConfig", + "NormalizedVertex", + "OperationMetadata", + "OutputConfig", + "PredictRequest", + "PredictResponse", + "PredictionServiceClient", + "TextClassificationDatasetMetadata", + "TextClassificationModelMetadata", + "TextExtractionAnnotation", + "TextExtractionDatasetMetadata", + "TextExtractionEvaluationMetrics", + "TextExtractionModelMetadata", + "TextSegment", + "TextSentimentAnnotation", + "TextSentimentDatasetMetadata", + "TextSentimentEvaluationMetrics", + "TextSentimentModelMetadata", + "TextSnippet", + "TranslationAnnotation", + "TranslationDatasetMetadata", + "TranslationEvaluationMetrics", + "TranslationModelMetadata", + "UndeployModelOperationMetadata", + "UndeployModelRequest", + "UpdateDatasetRequest", + "UpdateModelRequest", + "AutoMlClient", +) diff --git a/google/cloud/automl_v1/gapic/auto_ml_client.py b/google/cloud/automl_v1/gapic/auto_ml_client.py deleted file mode 100644 index c1f6ed3d..00000000 --- a/google/cloud/automl_v1/gapic/auto_ml_client.py +++ /dev/null @@ -1,1898 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.automl.v1 AutoMl API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import google.api_core.protobuf_helpers -import grpc - -from google.cloud.automl_v1.gapic import auto_ml_client_config -from google.cloud.automl_v1.gapic import enums -from google.cloud.automl_v1.gapic.transports import auto_ml_grpc_transport -from google.cloud.automl_v1.proto import annotation_spec_pb2 -from google.cloud.automl_v1.proto import dataset_pb2 -from google.cloud.automl_v1.proto import image_pb2 -from google.cloud.automl_v1.proto import io_pb2 -from google.cloud.automl_v1.proto import model_evaluation_pb2 -from google.cloud.automl_v1.proto import model_pb2 -from google.cloud.automl_v1.proto import operations_pb2 as proto_operations_pb2 -from google.cloud.automl_v1.proto import service_pb2 -from google.cloud.automl_v1.proto import service_pb2_grpc -from google.longrunning import operations_pb2 as longrunning_operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-automl").version - - -class AutoMlClient(object): - """ - AutoML Server API. - - The resource names are assigned by the server. The server never reuses - names that it has created after the resources with those names are - deleted. - - An ID of a resource is the last element of the item's resource name. For - ``projects/{project_id}/locations/{location_id}/datasets/{dataset_id}``, - then the id for the item is ``{dataset_id}``. - - Currently the only supported ``location_id`` is "us-central1". - - On any input that is documented to expect a string parameter in - snake\_case or kebab-case, either of those cases is accepted. - """ - - SERVICE_ADDRESS = "automl.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.automl.v1.AutoMl" - - @classmethod - def from_service_account_file(cls, filename, *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: - AutoMlClient: 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 - - @classmethod - def annotation_spec_path(cls, project, location, dataset, annotation_spec): - """Return a fully-qualified annotation_spec string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}", - project=project, - location=location, - dataset=dataset, - annotation_spec=annotation_spec, - ) - - @classmethod - def dataset_path(cls, project, location, dataset): - """Return a fully-qualified dataset string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/datasets/{dataset}", - project=project, - location=location, - dataset=dataset, - ) - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - @classmethod - def model_path(cls, project, location, model): - """Return a fully-qualified model string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/models/{model}", - project=project, - location=location, - model=model, - ) - - @classmethod - def model_evaluation_path(cls, project, location, model, model_evaluation): - """Return a fully-qualified model_evaluation string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_evaluation}", - project=project, - location=location, - model=model, - model_evaluation=model_evaluation, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.AutoMlGrpcTransport, - Callable[[~.Credentials, type], ~.AutoMlGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = auto_ml_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=auto_ml_grpc_transport.AutoMlGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = auto_ml_grpc_transport.AutoMlGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME] - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def create_dataset( - self, - parent, - dataset, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a dataset. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `dataset`: - >>> dataset = {} - >>> - >>> response = client.create_dataset(parent, dataset) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): The resource name of the project to create the dataset for. - dataset (Union[dict, ~google.cloud.automl_v1.types.Dataset]): The dataset to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.Dataset` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_dataset" not in self._inner_api_calls: - self._inner_api_calls[ - "create_dataset" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_dataset, - default_retry=self._method_configs["CreateDataset"].retry, - default_timeout=self._method_configs["CreateDataset"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.CreateDatasetRequest(parent=parent, dataset=dataset) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["create_dataset"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - dataset_pb2.Dataset, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def update_dataset( - self, - dataset, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a dataset. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> # TODO: Initialize `dataset`: - >>> dataset = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_dataset(dataset, update_mask) - - Args: - dataset (Union[dict, ~google.cloud.automl_v1.types.Dataset]): The dataset which replaces the resource on the server. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.Dataset` - update_mask (Union[dict, ~google.cloud.automl_v1.types.FieldMask]): Required. The update mask applies to the resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types.Dataset` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_dataset" not in self._inner_api_calls: - self._inner_api_calls[ - "update_dataset" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_dataset, - default_retry=self._method_configs["UpdateDataset"].retry, - default_timeout=self._method_configs["UpdateDataset"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.UpdateDatasetRequest( - dataset=dataset, update_mask=update_mask - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("dataset.name", dataset.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_dataset"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_dataset( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a dataset. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]') - >>> - >>> response = client.get_dataset(name) - - Args: - name (str): The resource name of the dataset to retrieve. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types.Dataset` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_dataset" not in self._inner_api_calls: - self._inner_api_calls[ - "get_dataset" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_dataset, - default_retry=self._method_configs["GetDataset"].retry, - default_timeout=self._method_configs["GetDataset"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetDatasetRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_dataset"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_datasets( - self, - parent, - filter_=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists datasets in a project. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_datasets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_datasets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): The resource name of the project from which to list datasets. - filter_ (str): An expression for filtering the results of the request. - - - ``dataset_metadata`` - for existence of the case (e.g. - image\_classification\_dataset\_metadata:\*). Some examples of using - the filter are: - - - ``translation_dataset_metadata:*`` --> The dataset has - translation\_dataset\_metadata. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.automl_v1.types.Dataset` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_datasets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_datasets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_datasets, - default_retry=self._method_configs["ListDatasets"].retry, - default_timeout=self._method_configs["ListDatasets"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ListDatasetsRequest( - parent=parent, filter=filter_, page_size=page_size - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_datasets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="datasets", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def delete_dataset( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a dataset and all of its contents. Returns empty response in the - ``response`` field when it completes, and ``delete_details`` in the - ``metadata`` field. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]') - >>> - >>> response = client.delete_dataset(name) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): The resource name of the dataset to delete. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_dataset" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_dataset" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_dataset, - default_retry=self._method_configs["DeleteDataset"].retry, - default_timeout=self._method_configs["DeleteDataset"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DeleteDatasetRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["delete_dataset"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def import_data( - self, - name, - input_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Imports data into a dataset. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]') - >>> - >>> # TODO: Initialize `input_config`: - >>> input_config = {} - >>> - >>> response = client.import_data(name, input_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Required. Dataset name. Dataset must already exist. All imported - annotations and examples will be added. - input_config (Union[dict, ~google.cloud.automl_v1.types.InputConfig]): Required. The desired input location and its domain specific semantics, - if any. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.InputConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "import_data" not in self._inner_api_calls: - self._inner_api_calls[ - "import_data" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.import_data, - default_retry=self._method_configs["ImportData"].retry, - default_timeout=self._method_configs["ImportData"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ImportDataRequest(name=name, input_config=input_config) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["import_data"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def export_data( - self, - name, - output_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Exports dataset's data to the provided output location. Returns an empty - response in the ``response`` field when it completes. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]') - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.export_data(name, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Required. The resource name of the dataset. - output_config (Union[dict, ~google.cloud.automl_v1.types.OutputConfig]): Required. The desired output location. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.OutputConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "export_data" not in self._inner_api_calls: - self._inner_api_calls[ - "export_data" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.export_data, - default_retry=self._method_configs["ExportData"].retry, - default_timeout=self._method_configs["ExportData"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ExportDataRequest(name=name, output_config=output_config) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["export_data"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def get_annotation_spec( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets an annotation spec. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.annotation_spec_path('[PROJECT]', '[LOCATION]', '[DATASET]', '[ANNOTATION_SPEC]') - >>> - >>> response = client.get_annotation_spec(name) - - Args: - name (str): The resource name of the annotation spec to retrieve. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types.AnnotationSpec` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_annotation_spec" not in self._inner_api_calls: - self._inner_api_calls[ - "get_annotation_spec" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_annotation_spec, - default_retry=self._method_configs["GetAnnotationSpec"].retry, - default_timeout=self._method_configs["GetAnnotationSpec"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetAnnotationSpecRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_annotation_spec"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_model( - self, - parent, - model, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a model. Returns a Model in the ``response`` field when it - completes. When you create a model, several model evaluations are - created for it: a global evaluation, and one evaluation for each - annotation spec. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `model`: - >>> model = {} - >>> - >>> response = client.create_model(parent, model) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Resource name of the parent project where the model is being created. - model (Union[dict, ~google.cloud.automl_v1.types.Model]): The model to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.Model` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_model" not in self._inner_api_calls: - self._inner_api_calls[ - "create_model" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_model, - default_retry=self._method_configs["CreateModel"].retry, - default_timeout=self._method_configs["CreateModel"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.CreateModelRequest(parent=parent, model=model) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["create_model"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - model_pb2.Model, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def get_model( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a model. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> response = client.get_model(name) - - Args: - name (str): Resource name of the model. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types.Model` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_model" not in self._inner_api_calls: - self._inner_api_calls[ - "get_model" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_model, - default_retry=self._method_configs["GetModel"].retry, - default_timeout=self._method_configs["GetModel"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetModelRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_model"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_model( - self, - model, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a model. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> # TODO: Initialize `model`: - >>> model = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_model(model, update_mask) - - Args: - model (Union[dict, ~google.cloud.automl_v1.types.Model]): The model which replaces the resource on the server. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.Model` - update_mask (Union[dict, ~google.cloud.automl_v1.types.FieldMask]): Required. The update mask applies to the resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types.Model` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_model" not in self._inner_api_calls: - self._inner_api_calls[ - "update_model" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_model, - default_retry=self._method_configs["UpdateModel"].retry, - default_timeout=self._method_configs["UpdateModel"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.UpdateModelRequest(model=model, update_mask=update_mask) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("model.name", model.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_model"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_models( - self, - parent, - filter_=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists models. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_models(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_models(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Resource name of the project, from which to list the models. - filter_ (str): An expression for filtering the results of the request. - - - ``model_metadata`` - for existence of the case (e.g. - image\_classification\_model\_metadata:\*). - - - ``dataset_id`` - for = or !=. Some examples of using the filter are: - - - ``image_classification_model_metadata:*`` --> The model has - image\_classification\_model\_metadata. - - - ``dataset_id=5`` --> The model was created from a dataset with ID 5. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.automl_v1.types.Model` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_models" not in self._inner_api_calls: - self._inner_api_calls[ - "list_models" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_models, - default_retry=self._method_configs["ListModels"].retry, - default_timeout=self._method_configs["ListModels"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ListModelsRequest( - parent=parent, filter=filter_, page_size=page_size - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_models"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="model", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def delete_model( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a model. Returns ``google.protobuf.Empty`` in the ``response`` - field when it completes, and ``delete_details`` in the ``metadata`` - field. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> response = client.delete_model(name) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Resource name of the model being deleted. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_model" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_model" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_model, - default_retry=self._method_configs["DeleteModel"].retry, - default_timeout=self._method_configs["DeleteModel"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DeleteModelRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["delete_model"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def deploy_model( - self, - name, - image_object_detection_model_deployment_metadata=None, - image_classification_model_deployment_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deploys a model. If a model is already deployed, deploying it with the - same parameters has no effect. Deploying with different parametrs (as - e.g. changing - - ``node_number``) will reset the deployment state without pausing the - model's availability. - - Only applicable for Text Classification, Image Object Detection; all - other domains manage deployment automatically. - - Returns an empty response in the ``response`` field when it completes. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> response = client.deploy_model(name) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Resource name of the model to deploy. - image_object_detection_model_deployment_metadata (Union[dict, ~google.cloud.automl_v1.types.ImageObjectDetectionModelDeploymentMetadata]): Model deployment metadata specific to Image Object Detection. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.ImageObjectDetectionModelDeploymentMetadata` - image_classification_model_deployment_metadata (Union[dict, ~google.cloud.automl_v1.types.ImageClassificationModelDeploymentMetadata]): Model deployment metadata specific to Image Classification. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.ImageClassificationModelDeploymentMetadata` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "deploy_model" not in self._inner_api_calls: - self._inner_api_calls[ - "deploy_model" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.deploy_model, - default_retry=self._method_configs["DeployModel"].retry, - default_timeout=self._method_configs["DeployModel"].timeout, - client_info=self._client_info, - ) - - # Sanity check: We have some fields which are mutually exclusive; - # raise ValueError if more than one is sent. - google.api_core.protobuf_helpers.check_oneof( - image_object_detection_model_deployment_metadata=image_object_detection_model_deployment_metadata, - image_classification_model_deployment_metadata=image_classification_model_deployment_metadata, - ) - - request = service_pb2.DeployModelRequest( - name=name, - image_object_detection_model_deployment_metadata=image_object_detection_model_deployment_metadata, - image_classification_model_deployment_metadata=image_classification_model_deployment_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["deploy_model"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def undeploy_model( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Undeploys a model. If the model is not deployed this method has no - effect. - - Only applicable for Text Classification, Image Object Detection; all - other domains manage deployment automatically. - - Returns an empty response in the ``response`` field when it completes. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> response = client.undeploy_model(name) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Resource name of the model to undeploy. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "undeploy_model" not in self._inner_api_calls: - self._inner_api_calls[ - "undeploy_model" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.undeploy_model, - default_retry=self._method_configs["UndeployModel"].retry, - default_timeout=self._method_configs["UndeployModel"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.UndeployModelRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["undeploy_model"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def export_model( - self, - name, - output_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Exports a trained, "export-able", model to a user specified Google Cloud - Storage location. A model is considered export-able if and only if it - has an export format defined for it in ``ModelExportOutputConfig``. - - Returns an empty response in the ``response`` field when it completes. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.export_model(name, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Required. The resource name of the model to export. - output_config (Union[dict, ~google.cloud.automl_v1.types.ModelExportOutputConfig]): Required. The desired output location and configuration. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.ModelExportOutputConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "export_model" not in self._inner_api_calls: - self._inner_api_calls[ - "export_model" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.export_model, - default_retry=self._method_configs["ExportModel"].retry, - default_timeout=self._method_configs["ExportModel"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ExportModelRequest(name=name, output_config=output_config) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["export_model"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=proto_operations_pb2.OperationMetadata, - ) - - def get_model_evaluation( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a model evaluation. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> name = client.model_evaluation_path('[PROJECT]', '[LOCATION]', '[MODEL]', '[MODEL_EVALUATION]') - >>> - >>> response = client.get_model_evaluation(name) - - Args: - name (str): Resource name for the model evaluation. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types.ModelEvaluation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_model_evaluation" not in self._inner_api_calls: - self._inner_api_calls[ - "get_model_evaluation" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_model_evaluation, - default_retry=self._method_configs["GetModelEvaluation"].retry, - default_timeout=self._method_configs["GetModelEvaluation"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetModelEvaluationRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_model_evaluation"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_model_evaluations( - self, - parent, - filter_, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists model evaluations. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.AutoMlClient() - >>> - >>> parent = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> # TODO: Initialize `filter_`: - >>> filter_ = '' - >>> - >>> # Iterate over all results - >>> for element in client.list_model_evaluations(parent, filter_): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_model_evaluations(parent, filter_).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Resource name of the model to list the model evaluations for. - If modelId is set as "-", this will list model evaluations from across all - models of the parent location. - filter_ (str): An expression for filtering the results of the request. - - - ``annotation_spec_id`` - for =, != or existence. See example below - for the last. - - Some examples of using the filter are: - - - ``annotation_spec_id!=4`` --> The model evaluation was done for - annotation spec with ID different than 4. - - ``NOT annotation_spec_id:*`` --> The model evaluation was done for - aggregate of all annotation specs. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.automl_v1.types.ModelEvaluation` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_model_evaluations" not in self._inner_api_calls: - self._inner_api_calls[ - "list_model_evaluations" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_model_evaluations, - default_retry=self._method_configs["ListModelEvaluations"].retry, - default_timeout=self._method_configs["ListModelEvaluations"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ListModelEvaluationsRequest( - parent=parent, filter=filter_, page_size=page_size - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_model_evaluations"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="model_evaluation", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator diff --git a/google/cloud/automl_v1/gapic/auto_ml_client_config.py b/google/cloud/automl_v1/gapic/auto_ml_client_config.py deleted file mode 100644 index e54353d4..00000000 --- a/google/cloud/automl_v1/gapic/auto_ml_client_config.py +++ /dev/null @@ -1,113 +0,0 @@ -config = { - "interfaces": { - "google.cloud.automl.v1.AutoMl": { - "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } - }, - "methods": { - "CreateDataset": { - "timeout_millis": 5000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "UpdateDataset": { - "timeout_millis": 5000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "GetDataset": { - "timeout_millis": 5000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "ListDatasets": { - "timeout_millis": 50000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "DeleteDataset": { - "timeout_millis": 5000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "ImportData": { - "timeout_millis": 20000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "ExportData": { - "timeout_millis": 5000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "GetAnnotationSpec": { - "timeout_millis": 5000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "CreateModel": { - "timeout_millis": 20000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "GetModel": { - "timeout_millis": 5000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "UpdateModel": { - "timeout_millis": 5000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "ListModels": { - "timeout_millis": 50000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "DeleteModel": { - "timeout_millis": 5000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "DeployModel": { - "timeout_millis": 5000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "UndeployModel": { - "timeout_millis": 5000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "ExportModel": { - "timeout_millis": 5000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "GetModelEvaluation": { - "timeout_millis": 5000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "ListModelEvaluations": { - "timeout_millis": 50000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - }, - } - } -} diff --git a/google/cloud/automl_v1/gapic/enums.py b/google/cloud/automl_v1/gapic/enums.py deleted file mode 100644 index 8e525587..00000000 --- a/google/cloud/automl_v1/gapic/enums.py +++ /dev/null @@ -1,109 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class ClassificationType(enum.IntEnum): - """ - Type of the classification problem. - - Attributes: - CLASSIFICATION_TYPE_UNSPECIFIED (int): An un-set value of this enum. - MULTICLASS (int): At most one label is allowed per example. - MULTILABEL (int): Multiple labels are allowed for one example. - """ - - CLASSIFICATION_TYPE_UNSPECIFIED = 0 - MULTICLASS = 1 - MULTILABEL = 2 - - -class Document(object): - class Layout(object): - class TextSegmentType(enum.IntEnum): - """ - The type of TextSegment in the context of the original document. - - Attributes: - TEXT_SEGMENT_TYPE_UNSPECIFIED (int): Should not be used. - TOKEN (int): The text segment is a token. e.g. word. - PARAGRAPH (int): The text segment is a paragraph. - FORM_FIELD (int): The text segment is a form field. - FORM_FIELD_NAME (int): The text segment is the name part of a form field. It will be treated as - child of another FORM\_FIELD TextSegment if its span is subspan of - another TextSegment with type FORM\_FIELD. - FORM_FIELD_CONTENTS (int): The text segment is the text content part of a form field. It will be - treated as child of another FORM\_FIELD TextSegment if its span is - subspan of another TextSegment with type FORM\_FIELD. - TABLE (int): The text segment is a whole table, including headers, and all rows. - TABLE_HEADER (int): The text segment is a table's headers. It will be treated as child of - another TABLE TextSegment if its span is subspan of another TextSegment - with type TABLE. - TABLE_ROW (int): The text segment is a row in table. It will be treated as child of - another TABLE TextSegment if its span is subspan of another TextSegment - with type TABLE. - TABLE_CELL (int): The text segment is a cell in table. It will be treated as child of - another TABLE\_ROW TextSegment if its span is subspan of another - TextSegment with type TABLE\_ROW. - """ - - TEXT_SEGMENT_TYPE_UNSPECIFIED = 0 - TOKEN = 1 - PARAGRAPH = 2 - FORM_FIELD = 3 - FORM_FIELD_NAME = 4 - FORM_FIELD_CONTENTS = 5 - TABLE = 6 - TABLE_HEADER = 7 - TABLE_ROW = 8 - TABLE_CELL = 9 - - -class DocumentDimensions(object): - class DocumentDimensionUnit(enum.IntEnum): - """ - Unit of the document dimension. - - Attributes: - DOCUMENT_DIMENSION_UNIT_UNSPECIFIED (int): Should not be used. - INCH (int): Document dimension is measured in inches. - CENTIMETER (int): Document dimension is measured in centimeters. - POINT (int): Document dimension is measured in points. 72 points = 1 inch. - """ - - DOCUMENT_DIMENSION_UNIT_UNSPECIFIED = 0 - INCH = 1 - CENTIMETER = 2 - POINT = 3 - - -class Model(object): - class DeploymentState(enum.IntEnum): - """ - Deployment state of the model. - - Attributes: - DEPLOYMENT_STATE_UNSPECIFIED (int): Should not be used, an un-set enum has this value by default. - DEPLOYED (int): Model is deployed. - UNDEPLOYED (int): Model is not deployed. - """ - - DEPLOYMENT_STATE_UNSPECIFIED = 0 - DEPLOYED = 1 - UNDEPLOYED = 2 diff --git a/google/cloud/automl_v1/gapic/prediction_service_client.py b/google/cloud/automl_v1/gapic/prediction_service_client.py deleted file mode 100644 index d6df5e54..00000000 --- a/google/cloud/automl_v1/gapic/prediction_service_client.py +++ /dev/null @@ -1,463 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.automl.v1 PredictionService API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.path_template -import grpc - -from google.cloud.automl_v1.gapic import enums -from google.cloud.automl_v1.gapic import prediction_service_client_config -from google.cloud.automl_v1.gapic.transports import prediction_service_grpc_transport -from google.cloud.automl_v1.proto import annotation_spec_pb2 -from google.cloud.automl_v1.proto import data_items_pb2 -from google.cloud.automl_v1.proto import dataset_pb2 -from google.cloud.automl_v1.proto import image_pb2 -from google.cloud.automl_v1.proto import io_pb2 -from google.cloud.automl_v1.proto import model_evaluation_pb2 -from google.cloud.automl_v1.proto import model_pb2 -from google.cloud.automl_v1.proto import operations_pb2 as proto_operations_pb2 -from google.cloud.automl_v1.proto import prediction_service_pb2 -from google.cloud.automl_v1.proto import prediction_service_pb2_grpc -from google.cloud.automl_v1.proto import service_pb2 -from google.cloud.automl_v1.proto import service_pb2_grpc -from google.longrunning import operations_pb2 as longrunning_operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-automl").version - - -class PredictionServiceClient(object): - """ - AutoML Prediction API. - - On any input that is documented to expect a string parameter in - snake\_case or kebab-case, either of those cases is accepted. - """ - - SERVICE_ADDRESS = "automl.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.automl.v1.PredictionService" - - @classmethod - def from_service_account_file(cls, filename, *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: - PredictionServiceClient: 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 - - @classmethod - def model_path(cls, project, location, model): - """Return a fully-qualified model string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/models/{model}", - project=project, - location=location, - model=model, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.PredictionServiceGrpcTransport, - Callable[[~.Credentials, type], ~.PredictionServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = prediction_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=prediction_service_grpc_transport.PredictionServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = prediction_service_grpc_transport.PredictionServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME] - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def predict( - self, - name, - payload, - params=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Perform an online prediction. The prediction result will be directly - returned in the response. Available for following ML problems, and their - expected request payloads: - - - Image Classification - Image in .JPEG, .GIF or .PNG format, - image\_bytes up to 30MB. - - Image Object Detection - Image in .JPEG, .GIF or .PNG format, - image\_bytes up to 30MB. - - Text Classification - TextSnippet, content up to 60,000 characters, - UTF-8 encoded. - - Text Extraction - TextSnippet, content up to 30,000 characters, UTF-8 - NFC encoded. - - Translation - TextSnippet, content up to 25,000 characters, UTF-8 - encoded. - - Text Sentiment - TextSnippet, content up 500 characters, UTF-8 - encoded. - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.PredictionServiceClient() - >>> - >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> # TODO: Initialize `payload`: - >>> payload = {} - >>> - >>> response = client.predict(name, payload) - - Args: - name (str): Name of the model requested to serve the prediction. - payload (Union[dict, ~google.cloud.automl_v1.types.ExamplePayload]): Required. Payload to perform a prediction on. The payload must match the - problem type that the model was trained to solve. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.ExamplePayload` - params (dict[str -> str]): Additional domain-specific parameters, any string must be up to 25000 - characters long. - - - For Image Classification: - - ``score_threshold`` - (float) A value from 0.0 to 1.0. When the model - makes predictions for an image, it will only produce results that - have at least this confidence score. The default is 0.5. - - - For Image Object Detection: ``score_threshold`` - (float) When Model - detects objects on the image, it will only produce bounding boxes - which have at least this confidence score. Value in 0 to 1 range, - default is 0.5. ``max_bounding_box_count`` - (int64) No more than - this number of bounding boxes will be returned in the response. - Default is 100, the requested value may be limited by server. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types.PredictResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "predict" not in self._inner_api_calls: - self._inner_api_calls[ - "predict" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.predict, - default_retry=self._method_configs["Predict"].retry, - default_timeout=self._method_configs["Predict"].timeout, - client_info=self._client_info, - ) - - request = prediction_service_pb2.PredictRequest( - name=name, payload=payload, params=params - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["predict"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def batch_predict( - self, - name, - input_config, - output_config, - params=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Perform a batch prediction. Unlike the online ``Predict``, batch - prediction result won't be immediately available in the response. - Instead, a long running operation object is returned. User can poll the - operation result via ``GetOperation`` method. Once the operation is - done, ``BatchPredictResult`` is returned in the ``response`` field. - Available for following ML problems: - - - Image Classification - - Image Object Detection - - Text Extraction - - Example: - >>> from google.cloud import automl_v1 - >>> - >>> client = automl_v1.PredictionServiceClient() - >>> - >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') - >>> - >>> # TODO: Initialize `input_config`: - >>> input_config = {} - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.batch_predict(name, input_config, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Name of the model requested to serve the batch prediction. - input_config (Union[dict, ~google.cloud.automl_v1.types.BatchPredictInputConfig]): Required. The input configuration for batch prediction. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.BatchPredictInputConfig` - output_config (Union[dict, ~google.cloud.automl_v1.types.BatchPredictOutputConfig]): Required. The Configuration specifying where output predictions should - be written. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.automl_v1.types.BatchPredictOutputConfig` - params (dict[str -> str]): Additional domain-specific parameters for the predictions, any string - must be up to 25000 characters long. - - - For Text Classification: - - ``score_threshold`` - (float) A value from 0.0 to 1.0. When the model - makes predictions for a text snippet, it will only produce results - that have at least this confidence score. The default is 0.5. - - - For Image Classification: - - ``score_threshold`` - (float) A value from 0.0 to 1.0. When the model - makes predictions for an image, it will only produce results that - have at least this confidence score. The default is 0.5. - - - For Image Object Detection: - - ``score_threshold`` - (float) When Model detects objects on the - image, it will only produce bounding boxes which have at least this - confidence score. Value in 0 to 1 range, default is 0.5. - ``max_bounding_box_count`` - (int64) No more than this number of - bounding boxes will be produced per image. Default is 100, the - requested value may be limited by server. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.automl_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_predict" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_predict" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_predict, - default_retry=self._method_configs["BatchPredict"].retry, - default_timeout=self._method_configs["BatchPredict"].timeout, - client_info=self._client_info, - ) - - request = prediction_service_pb2.BatchPredictRequest( - name=name, - input_config=input_config, - output_config=output_config, - params=params, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["batch_predict"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - prediction_service_pb2.BatchPredictResult, - metadata_type=proto_operations_pb2.OperationMetadata, - ) diff --git a/google/cloud/automl_v1/gapic/prediction_service_client_config.py b/google/cloud/automl_v1/gapic/prediction_service_client_config.py deleted file mode 100644 index bcfb22ff..00000000 --- a/google/cloud/automl_v1/gapic/prediction_service_client_config.py +++ /dev/null @@ -1,33 +0,0 @@ -config = { - "interfaces": { - "google.cloud.automl.v1.PredictionService": { - "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } - }, - "methods": { - "Predict": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "BatchPredict": { - "timeout_millis": 20000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - }, - } - } -} diff --git a/google/cloud/automl_v1/gapic/transports/__init__.py b/google/cloud/automl_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/automl_v1/gapic/transports/auto_ml_grpc_transport.py b/google/cloud/automl_v1/gapic/transports/auto_ml_grpc_transport.py deleted file mode 100644 index c5f6bfa7..00000000 --- a/google/cloud/automl_v1/gapic/transports/auto_ml_grpc_transport.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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.automl_v1.proto import service_pb2_grpc - - -class AutoMlGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.automl.v1 AutoMl API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="automl.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive." - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = {"auto_ml_stub": service_pb2_grpc.AutoMlStub(channel)} - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="automl.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def create_dataset(self): - """Return the gRPC stub for :meth:`AutoMlClient.create_dataset`. - - Creates a dataset. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].CreateDataset - - @property - def update_dataset(self): - """Return the gRPC stub for :meth:`AutoMlClient.update_dataset`. - - Updates a dataset. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].UpdateDataset - - @property - def get_dataset(self): - """Return the gRPC stub for :meth:`AutoMlClient.get_dataset`. - - Gets a dataset. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].GetDataset - - @property - def list_datasets(self): - """Return the gRPC stub for :meth:`AutoMlClient.list_datasets`. - - Lists datasets in a project. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].ListDatasets - - @property - def delete_dataset(self): - """Return the gRPC stub for :meth:`AutoMlClient.delete_dataset`. - - Deletes a dataset and all of its contents. Returns empty response in the - ``response`` field when it completes, and ``delete_details`` in the - ``metadata`` field. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].DeleteDataset - - @property - def import_data(self): - """Return the gRPC stub for :meth:`AutoMlClient.import_data`. - - Imports data into a dataset. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].ImportData - - @property - def export_data(self): - """Return the gRPC stub for :meth:`AutoMlClient.export_data`. - - Exports dataset's data to the provided output location. Returns an empty - response in the ``response`` field when it completes. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].ExportData - - @property - def get_annotation_spec(self): - """Return the gRPC stub for :meth:`AutoMlClient.get_annotation_spec`. - - Gets an annotation spec. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].GetAnnotationSpec - - @property - def create_model(self): - """Return the gRPC stub for :meth:`AutoMlClient.create_model`. - - Creates a model. Returns a Model in the ``response`` field when it - completes. When you create a model, several model evaluations are - created for it: a global evaluation, and one evaluation for each - annotation spec. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].CreateModel - - @property - def get_model(self): - """Return the gRPC stub for :meth:`AutoMlClient.get_model`. - - Gets a model. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].GetModel - - @property - def update_model(self): - """Return the gRPC stub for :meth:`AutoMlClient.update_model`. - - Updates a model. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].UpdateModel - - @property - def list_models(self): - """Return the gRPC stub for :meth:`AutoMlClient.list_models`. - - Lists models. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].ListModels - - @property - def delete_model(self): - """Return the gRPC stub for :meth:`AutoMlClient.delete_model`. - - Deletes a model. Returns ``google.protobuf.Empty`` in the ``response`` - field when it completes, and ``delete_details`` in the ``metadata`` - field. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].DeleteModel - - @property - def deploy_model(self): - """Return the gRPC stub for :meth:`AutoMlClient.deploy_model`. - - Deploys a model. If a model is already deployed, deploying it with the - same parameters has no effect. Deploying with different parametrs (as - e.g. changing - - ``node_number``) will reset the deployment state without pausing the - model's availability. - - Only applicable for Text Classification, Image Object Detection; all - other domains manage deployment automatically. - - Returns an empty response in the ``response`` field when it completes. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].DeployModel - - @property - def undeploy_model(self): - """Return the gRPC stub for :meth:`AutoMlClient.undeploy_model`. - - Undeploys a model. If the model is not deployed this method has no - effect. - - Only applicable for Text Classification, Image Object Detection; all - other domains manage deployment automatically. - - Returns an empty response in the ``response`` field when it completes. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].UndeployModel - - @property - def export_model(self): - """Return the gRPC stub for :meth:`AutoMlClient.export_model`. - - Exports a trained, "export-able", model to a user specified Google Cloud - Storage location. A model is considered export-able if and only if it - has an export format defined for it in ``ModelExportOutputConfig``. - - Returns an empty response in the ``response`` field when it completes. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].ExportModel - - @property - def get_model_evaluation(self): - """Return the gRPC stub for :meth:`AutoMlClient.get_model_evaluation`. - - Gets a model evaluation. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].GetModelEvaluation - - @property - def list_model_evaluations(self): - """Return the gRPC stub for :meth:`AutoMlClient.list_model_evaluations`. - - Lists model evaluations. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["auto_ml_stub"].ListModelEvaluations diff --git a/google/cloud/automl_v1/gapic/transports/prediction_service_grpc_transport.py b/google/cloud/automl_v1/gapic/transports/prediction_service_grpc_transport.py deleted file mode 100644 index 9d494540..00000000 --- a/google/cloud/automl_v1/gapic/transports/prediction_service_grpc_transport.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.automl_v1.proto import prediction_service_pb2_grpc - - -class PredictionServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.automl.v1 PredictionService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="automl.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive." - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "prediction_service_stub": prediction_service_pb2_grpc.PredictionServiceStub( - channel - ) - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="automl.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def predict(self): - """Return the gRPC stub for :meth:`PredictionServiceClient.predict`. - - Perform an online prediction. The prediction result will be directly - returned in the response. Available for following ML problems, and their - expected request payloads: - - - Image Classification - Image in .JPEG, .GIF or .PNG format, - image\_bytes up to 30MB. - - Image Object Detection - Image in .JPEG, .GIF or .PNG format, - image\_bytes up to 30MB. - - Text Classification - TextSnippet, content up to 60,000 characters, - UTF-8 encoded. - - Text Extraction - TextSnippet, content up to 30,000 characters, UTF-8 - NFC encoded. - - Translation - TextSnippet, content up to 25,000 characters, UTF-8 - encoded. - - Text Sentiment - TextSnippet, content up 500 characters, UTF-8 - encoded. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["prediction_service_stub"].Predict - - @property - def batch_predict(self): - """Return the gRPC stub for :meth:`PredictionServiceClient.batch_predict`. - - Perform a batch prediction. Unlike the online ``Predict``, batch - prediction result won't be immediately available in the response. - Instead, a long running operation object is returned. User can poll the - operation result via ``GetOperation`` method. Once the operation is - done, ``BatchPredictResult`` is returned in the ``response`` field. - Available for following ML problems: - - - Image Classification - - Image Object Detection - - Text Extraction - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["prediction_service_stub"].BatchPredict diff --git a/google/cloud/automl_v1/proto/__init__.py b/google/cloud/automl_v1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/automl_v1/proto/annotation_payload.proto b/google/cloud/automl_v1/proto/annotation_payload.proto index 980c0e36..a81feaf1 100644 --- a/google/cloud/automl_v1/proto/annotation_payload.proto +++ b/google/cloud/automl_v1/proto/annotation_payload.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// 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. @@ -11,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// syntax = "proto3"; diff --git a/google/cloud/automl_v1/proto/annotation_payload_pb2.py b/google/cloud/automl_v1/proto/annotation_payload_pb2.py deleted file mode 100644 index 7840971f..00000000 --- a/google/cloud/automl_v1/proto/annotation_payload_pb2.py +++ /dev/null @@ -1,315 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/automl_v1/proto/annotation_payload.proto - -import sys - -_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.cloud.automl_v1.proto import ( - classification_pb2 as google_dot_cloud_dot_automl__v1_dot_proto_dot_classification__pb2, -) -from google.cloud.automl_v1.proto import ( - detection_pb2 as google_dot_cloud_dot_automl__v1_dot_proto_dot_detection__pb2, -) -from google.cloud.automl_v1.proto import ( - text_extraction_pb2 as google_dot_cloud_dot_automl__v1_dot_proto_dot_text__extraction__pb2, -) -from google.cloud.automl_v1.proto import ( - text_sentiment_pb2 as google_dot_cloud_dot_automl__v1_dot_proto_dot_text__sentiment__pb2, -) -from google.cloud.automl_v1.proto import ( - translation_pb2 as google_dot_cloud_dot_automl__v1_dot_proto_dot_translation__pb2, -) -from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/automl_v1/proto/annotation_payload.proto", - package="google.cloud.automl.v1", - syntax="proto3", - serialized_options=_b( - "\n\032com.google.cloud.automl.v1P\001Z // // +//

AutoML Video Intelligence

+// +// +//
Classification
+// +// See [Preparing your training +// data](https://cloud.google.com/video-intelligence/automl/docs/prepare) for +// more information. +// +// CSV file(s) with each line in format: +// +// ML_USE,GCS_FILE_PATH +// +// For `ML_USE`, do not use `VALIDATE`. +// +// `GCS_FILE_PATH` is the path to another .csv file that describes training +// example for a given `ML_USE`, using the following row format: +// +// GCS_FILE_PATH,(LABEL,TIME_SEGMENT_START,TIME_SEGMENT_END | ,,) +// +// Here `GCS_FILE_PATH` leads to a video of up to 50GB in size and up +// to 3h duration. Supported extensions: .MOV, .MPEG4, .MP4, .AVI. +// +// `TIME_SEGMENT_START` and `TIME_SEGMENT_END` must be within the +// length of the video, and the end time must be after the start time. Any +// segment of a video which has one or more labels on it, is considered a +// hard negative for all other labels. Any segment with no labels on +// it is considered to be unknown. If a whole video is unknown, then +// it should be mentioned just once with ",," in place of `LABEL, +// TIME_SEGMENT_START,TIME_SEGMENT_END`. +// +// Sample top level CSV file: +// +// TRAIN,gs://folder/train_videos.csv +// TEST,gs://folder/test_videos.csv +// UNASSIGNED,gs://folder/other_videos.csv +// +// Sample rows of a CSV file for a particular ML_USE: +// +// gs://folder/video1.avi,car,120,180.000021 +// gs://folder/video1.avi,bike,150,180.000021 +// gs://folder/vid2.avi,car,0,60.5 +// gs://folder/vid3.avi,,, +// +// +// +//
Object Tracking
+// +// See [Preparing your training +// data](/video-intelligence/automl/object-tracking/docs/prepare) for more +// information. +// +// CSV file(s) with each line in format: +// +// ML_USE,GCS_FILE_PATH +// +// For `ML_USE`, do not use `VALIDATE`. +// +// `GCS_FILE_PATH` is the path to another .csv file that describes training +// example for a given `ML_USE`, using the following row format: +// +// GCS_FILE_PATH,LABEL,[INSTANCE_ID],TIMESTAMP,BOUNDING_BOX +// +// or +// +// GCS_FILE_PATH,,,,,,,,,, +// +// Here `GCS_FILE_PATH` leads to a video of up to 50GB in size and up +// to 3h duration. Supported extensions: .MOV, .MPEG4, .MP4, .AVI. +// Providing `INSTANCE_ID`s can help to obtain a better model. When +// a specific labeled entity leaves the video frame, and shows up +// afterwards it is not required, albeit preferable, that the same +// `INSTANCE_ID` is given to it. +// +// `TIMESTAMP` must be within the length of the video, the +// `BOUNDING_BOX` is assumed to be drawn on the closest video's frame +// to the `TIMESTAMP`. Any mentioned by the `TIMESTAMP` frame is expected +// to be exhaustively labeled and no more than 500 `BOUNDING_BOX`-es per +// frame are allowed. If a whole video is unknown, then it should be +// mentioned just once with ",,,,,,,,,," in place of `LABEL, +// [INSTANCE_ID],TIMESTAMP,BOUNDING_BOX`. +// +// Sample top level CSV file: +// +// TRAIN,gs://folder/train_videos.csv +// TEST,gs://folder/test_videos.csv +// UNASSIGNED,gs://folder/other_videos.csv +// +// Seven sample rows of a CSV file for a particular ML_USE: +// +// gs://folder/video1.avi,car,1,12.10,0.8,0.8,0.9,0.8,0.9,0.9,0.8,0.9 +// gs://folder/video1.avi,car,1,12.90,0.4,0.8,0.5,0.8,0.5,0.9,0.4,0.9 +// gs://folder/video1.avi,car,2,12.10,.4,.2,.5,.2,.5,.3,.4,.3 +// gs://folder/video1.avi,car,2,12.90,.8,.2,,,.9,.3,, +// gs://folder/video1.avi,bike,,12.50,.45,.45,,,.55,.55,, +// gs://folder/video2.avi,car,1,0,.1,.9,,,.9,.1,, +// gs://folder/video2.avi,,,,,,,,,,, +//
+//
+// +// //

AutoML Natural Language

// // @@ -223,9 +322,11 @@ option ruby_package = "Google::Cloud::AutoML::V1"; // **JSONL files that reference documents** // // .JSONL files contain, per line, a JSON document that wraps a -// `input_config` that contains the path to a source PDF document. +// `input_config` that contains the path to a source document. // Multiple JSON documents can be separated using line breaks (\n). // +// Supported document extensions: .PDF, .TIF, .TIFF +// // For example: // // { @@ -239,19 +340,19 @@ option ruby_package = "Google::Cloud::AutoML::V1"; // { // "document": { // "input_config": { -// "gcs_source": { "input_uris": [ "gs://folder/document2.pdf" ] +// "gcs_source": { "input_uris": [ "gs://folder/document2.tif" ] // } // } // } // } // -// **In-line JSONL files with PDF layout information** +// **In-line JSONL files with document layout information** // -// **Note:** You can only annotate PDF files using the UI. The format described -// below applies to annotated PDF files exported using the UI or `exportData`. +// **Note:** You can only annotate documents using the UI. The format described +// below applies to annotated documents exported using the UI or `exportData`. // -// In-line .JSONL files for PDF documents contain, per line, a JSON document -// that wraps a `document` field that provides the textual content of the PDF +// In-line .JSONL files for documents contain, per line, a JSON document +// that wraps a `document` field that provides the textual content of the // document and the layout information. // // For example: @@ -342,8 +443,9 @@ option ruby_package = "Google::Cloud::AutoML::V1"; // 10MB or less in size. // // For the `MULTICLASS` classification type, at most one `LABEL` is allowed. +// // The `ML_USE` and `LABEL` columns are optional. -// Supported file extensions: .TXT, .PDF, .ZIP +// Supported file extensions: .TXT, .PDF, .TIF, .TIFF, .ZIP // // A maximum of 100 unique labels are allowed per CSV row. // @@ -388,7 +490,7 @@ option ruby_package = "Google::Cloud::AutoML::V1"; // 128kB or less in size. // // The `ML_USE` and `SENTIMENT` columns are optional. -// Supported file extensions: .TXT, .PDF, .ZIP +// Supported file extensions: .TXT, .PDF, .TIF, .TIFF, .ZIP // // * `SENTIMENT` - An integer between 0 and // Dataset.text_sentiment_dataset_metadata.sentiment_max @@ -417,6 +519,54 @@ option ruby_package = "Google::Cloud::AutoML::V1"; //